我有一个对象数组,我希望在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;
答案 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')
。
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;
您也可以使用
map
数组方法。
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;