2014-11-20 35 views
1

我想缩短我的代码,并且卡住了。我有一个测验,并为每个问题的答案加载。但我想有一个变量可以为我做到这一点。使用变量作为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); 
}...... 

正如你可以看到它非常多余的,所以我认为包括变量“NR”有问题的数量的信息。所以,我想是这样的:

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

级联+nr+不工作,因为它不直接到正确的JSON内容。

回答

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

首先,当你说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"] 
     } 
    ] 
} 

这将组织你的数据转换成数组,这似乎更好地为这个数据符合您的使用案例。

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'] 
} 
      ]