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
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.
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); }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.