遍历数组对象

时间:2020-05-02 15:07:36

标签: javascript arrays for-loop 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说:未捕获的TypeError:无法读取未定义的属性'length'

3 个答案:

答案 0 :(得分:1)

似乎变量问题未包含在同一文件中。

答案 1 :(得分:0)

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
})

答案 2 :(得分:0)

用于..:

cmp