使用变量作为JSON密钥

时间:2014-11-20 17:48:34

标签: javascript json

我想缩短我的代码而且我被困住了。我有一个测验,每个问题都会加载答案。但是我希望有一个变量为我做这个。

以下是代码:

if (nr === 1) {
    $('#questionmobile').html(content.inst3.question1);
    $('#answer1').html(content.inst3.q1a1);
    $('#answer2').html(content.inst3.q1a2);
    $('#answer3').html(content.inst3.q1a3);
    $('#answer4').html(content.inst3.q1a4);
} else if (nr === 2) {
    $('#questionmobile').html(content.inst3.question2);
    $('#answer1').html(content.inst3.q2a1);
    $('#answer2').html(content.inst3.q2a2);
    $('#answer3').html(content.inst3.q2a3);
    $('#answer4').html(content.inst3.q2a4);
}......

你可以看到它非常冗余,所以我想把变量包括在内#34; nr"具有问题数量的信息。所以我想要这样的东西:

$('#questionmobile').html(content.inst3.question+nr);
$('#answer1').html(content.inst3.q+nr+a1);

连接+nr+不起作用,因为它没有指向正确的JSON内容。

3 个答案:

答案 0 :(得分:4)

如果要将变量用作键,可以使用括号表示法(如数组[])。

$('#questionmobile').html(content.inst3['question'+nr]);
$('#answer1').html(content.inst3['q'+nr+'a1']);

您甚至可以使用循环来获得答案:

$('#questionmobile').html(content.inst3['question'+nr]);

var i, numAnswers = 4;
for(i = 1; i <= numAnswers; i++) {
    $('#answer' + i).html(content.inst3['q'+nr+'a'+i]);
}

答案 1 :(得分:1)

首先,当你说content.inst3.q+nr+a1 JavaScript将其解释为(content.inst3.q)+(nr)+(a1)时,它会将不存在的变量添加到一起。

您提出的问题的答案是您可以使用括号通过字符串名称访问对象中的字段。例如:

var x = {name: "Joe", age:56};
alert(x["name"]); //Outputs Joe
alert(x["age"]); //Outputs 56

您可以使用相同的技术撰写与您的模式匹配的字符串。但是,这可能不是最好的方法。您可能应该重新构建输入数据,以便您不需要使用此技术。例如,您可以将数据看起来像:

{
    "questions": [
        {
            "prompt": "Who was the first president of the US?",
            "answers": ["George Washington", "Abraham Lincoln", "Captain America", "The Hulk"]
        }
    ]
}

这会将您的数据构建到数组中,这似乎更符合您对此数据的使用情况。

答案 2 :(得分:0)

谢谢你们,两个答案都有帮助。我的解决方案是你的答案的混合。

$('#questionmobile').html(content.inst3.questions[nr - 1].question);
var i, numAnswers = 3;
for (i = 0; i <= numAnswers; i++) {
$('#answer' + (i + 1)).html(content.inst3.questions[nr - 1].answers[i]);
}

我清理了我的JSON结构:

"questions":[
 {
       "question":"bla?",
       "answers":["Toto Arno",'Anders Thomas','Tadao Ando','Tadaaa Anden']
 },
 {
       "question":'bli?',
       "answers":["Wasser",'Papier','Stein','Schere']
 },
 {
       "question":'blu?',
       "answers":["Deutschland",'Niederlande','Bosnien und Herzegowina','S&uuml;dkorea']
 }
           ]
相关问题