0

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

2
  • 1
    Can you create a small demo for this using jsfiddle or snippet here to show the issue happening. Commented May 2, 2020 at 15:09
  • I try to reproduce your solution and everything is good. Maybe you didn`t export questions? Commented May 3, 2020 at 7:05

3 Answers 3

1

It looks like the variable questions is not included in the same file.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.