无法遍历对象

时间:2019-05-07 14:01:03

标签: javascript object

我有一个带有各种对象的对象文字,但是我无法在网页中显示这些值。我尝试过“ for循环”方法,但它仅显示一个值。我想显示问题对象中的所有问题属性,但是使用此代码,我只能显示一个属性。

let questions = [{
    question: "Jinnah's first salary",
    choice1: 'Rs-1',
    choice2: 'Rs-1000',
    choice3: 'Rs-10000',
    choice4: 'Rs-100,000',
    correct: 'A'
  },
  {
    question: "First recognised Pakistan",
    choice1: 'USA',
    choice2: 'Iran',
    choice3: 'China',
    choice4: 'None',
    correct: 'B'
  },
  {
    question: "National bird",
    choice1: 'Bee',
    choice2: 'Parrot',
    choice3: 'Chokor',
    choice4: 'Peagon',
    correct: 'C'
  },
];


for (let i = 0; i <= questions.length; i++) {
  document.querySelector('.p').innerText = questions[i].question;
}
<!DOCTYPE html>
<html lang="en">
<body>
  <div class="p"></div>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

  1. =循环中删除for,因为数组是zero based,所以您想从0开始向下移动到数组长度。在您的情况下,数组长度为3,因此最后一项将为questions[2]。因此,循环应从02,而不是3

  2. 在分配+之前添加innerText,以便将新文本添加到已经存在的文本中(了解Addition assignment)。

let questions = [{
    question: "Jinnah's first salary",
    choice1: 'Rs-1',
    choice2: 'Rs-1000',
    choice3: 'Rs-10000',
    choice4: 'Rs-100,000',
    correct: 'A'
  },
  {
    question: "First recognised Pakistan",
    choice1: 'USA',
    choice2: 'Iran',
    choice3: 'China',
    choice4: 'None',
    correct: 'B'
  },
  {
    question: "National bird",
    choice1: 'Bee',
    choice2: 'Parrot',
    choice3: 'Chokor',
    choice4: 'Peagon',
    correct: 'C'
  },
];


for (let i = 0; i < questions.length; i++) {
  document.querySelector('.p').innerText += questions[i].question;
}
<!DOCTYPE html>
<html lang="en">
<body>
  <div class="p"></div>
</body>
</html>

答案 1 :(得分:0)

如果每个问题要有一个段落,则必须将每个段落生成为HTML,例如:

for (var i = 0; i < questions.length; i++) {  
   document.querySelector('body').innerHTML += "<p>"+questions[i].question+"</p>";
}