通过'for in'获取javascript中对象的键和值

时间:2014-05-02 02:50:21

标签: javascript arrays json object

我开始练习在javascript中创建一个测验。无论如何,我有一个包含问题的数组;每个问题都是一个匿名对象......

var allQuestions = [{
"question": "Who was Luke's wingman in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0},
{
"question": "What is the registry of the Starship Reliant?",
"choices": [ "NX-01", "NCC-1864", "NCC-1701", "NCC-2000"],
"correctAnswer": 1}...etc.

此时我想简单地遍历它们并将它们插入到DOM中。

var output = '';

for (key in allQuestions[0]) {
        output += '<li>' + allQuestions[0] + '</li>';
    }

 var update = document.getElementById("question");

 update.innerHTML = output;

但我得到的只是:

[object Object]
[object Object]
[object Object]

在某些时候,我想要匹配或者提出问题,选择&#39;流入页面上的相应元素....

<h2>question</h2> //question from object
<ul id="question">
 <li>choice</li> //choice from object
 <li>choice</li>
 <li>choice</li>
 <li>choice</li>

1 个答案:

答案 0 :(得分:2)

你在循环中使用allQuestions[0],但你可能想要引用key

for (key in allQuestions[0]) {
    output += '<li>' + key + '</li>';
}

但是,这将返回questionchoicescorrectAnswer。如果allQuestions中的项目采用相同的格式,则最好将其循环并引用相关属性:

for (var i = 0; i < allQuestions.length; i++) { 
  var item = allQuestions[i];
  console.log(item.question);
  console.log(item.choices);
  // etc. 
}