[英]Loop through array object
我正在尝试遍历这个数组
var questions = [
{
ask: 'is Javascript the best language?',
correct: 0,
answer : [
{text: 'yes'},
{text: 'No'}
]
},
{
ask: 'is Javascript the most popular language?',
correct: 1,
answer : [
{text: 'yes'},
{text: 'No'}
]
},
]
关键是我想用这个循环得到每一个问题,并在控制台日志中得到这些问题
var currentQuestion = questions.length;
for( var i = 0; i < currentQuestion; i++){
console.log(questions[i]);
}
但console.log 说:未捕获的类型错误:无法读取未定义的属性“长度”
看起来可变问题未包含在同一个文件中。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects上有关 js 对象的更多信息。
var questions = [ { ask: 'is Javascript the best language?', correct: 0, answer: [ {text: 'yes'}, {text: 'No'} ] }, { ask: 'is Javascript the most popular language?', correct: 1, answer: [ {text: 'yes'}, {text: 'No'} ] }, ]; var currentQuestion = questions.length; for( var i = 0; i < currentQuestion; i++){ console.log(questions[i].ask); } // es6 way questions.map(q => { // console.log(q.ask); // will get all the questions })
用于...:
var questions = [ { ask: 'is Javascript the best language?', correct: 0, answer: [ {text: 'yes'}, {text: 'No'} ] }, { ask: 'is Javascript the most popular language?', correct: 1, answer: [ {text: 'yes'}, {text: 'No'} ] }, ] for(let values of questions){ console.log(values); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.