成功循环遍历一系列对象

时间:2018-03-28 08:22:17

标签: javascript

我有一个对象数组,我希望在foreach的帮助下从中循环但是我得到了数组我不知道为什么。
我想在div中显示我的数组。

这是我的代码:



var questions = [{
    question: 'my name is?',
    answere: ['jame', 'rock', 'batista', 'micheal'],
    correctAnswere: 'Ahmad'
  },
  {
    question: 'your name is?',
    answere: ['jhon', 'rock', 'watson', 'cook'],
    correctAnswere: 'Ahmad'
  }];
var getquiz = document.getElementById('demo')
questions.forEach(function(arrayitem) {
  getquiz = getquiz.innerHTML + arrayitem.question + "<br>";
});
&#13;
<div id="getquiz">

</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

这是因为您要将getquiz dom元素替换为string连接到innerHTML属性的instated。 另外,getElementById中的选择器是错误的。

这是一个正确的代码段:

var questions=[{
    question:'my name is?',
    answere:['jame','rock','batista','micheal'],
    correctAnswere:'Ahmad'
  },
  {
    question:'your name is?',
    answere:['jhon','rock','watson','cook'],
    correctAnswere:'Ahmad'
  }
];

var getquiz=document.getElementById('getquiz');
questions.forEach(function (arrayitem)
{
  getquiz.innerHTML += arrayitem.question+"<br>";
});
<body>
    <div id="getquiz">

    </div>
</body>

答案 1 :(得分:0)

您的代码中的更正是您错误document.getElementById('demo')而不是您需要获取document.getElementById('getquiz')

&#13;
&#13;
var questions = [{
    question: 'my name is?',
    answere: ['jame', 'rock', 'batista', 'micheal'],
    correctAnswere: 'Ahmad'
  },
  {
    question: 'your name is?',
    answere: ['jhon', 'rock', 'watson', 'cook'],
    correctAnswere: 'Ahmad'
  }
];

var getquiz = document.getElementById('getquiz')
questions.forEach(function(arrayitem) {
  getquiz.innerHTML += arrayitem.question + "<br>";
});
&#13;
<div id="getquiz">

</div>
&#13;
&#13;
&#13;

  

您也可以使用map 数组方法。

&#13;
&#13;
const questions = [{
  question: 'my name is?',
  answere: ['jame', 'rock', 'batista', 'micheal'],
  correctAnswere: 'Ahmad'
}, {
  question: 'your name is?',
  answere: ['jhon', 'rock', 'watson', 'cook'],
  correctAnswere: 'Ahmad'
}];

let getquiz = questions.map(item => {
  return item.question;
});

document.getElementById('getquiz').innerHTML = getquiz.join('<br>');
&#13;
<div id="getquiz">

</div>
&#13;
&#13;
&#13;