简体   繁体   English

循环阵列 object

[英]Loop through array object

I am trying to loop through this array我正在尝试遍历这个数组

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'}
        ]
    },

]

and the point is I want to get every question with this loop and get these questions in console log关键是我想用这个循环得到每一个问题,并在控制台日志中得到这些问题

var currentQuestion = questions.length;

for( var i = 0; i < currentQuestion; i++){
   console.log(questions[i]);
}

but console.log says: Uncaught TypeError: Cannot read property 'length' of undefined但console.log 说:未捕获的类型错误:无法读取未定义的属性“长度”

It looks like the variable questions is not included in the same file.看起来可变问题未包含在同一个文件中。

more information at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects about the js objects. 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 })

Use for of.. :用于...:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM