[英]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.