Reputation: 96
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
Upvotes: 0
Views: 38
Reputation: 25
It looks like the variable questions is not included in the same file.
Upvotes: 1
Reputation: 877
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);
}
Upvotes: 0
Reputation: 1855
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
})
Upvotes: 0