L oop через массив объектов - PullRequest
0 голосов
/ 02 мая 2020

Я пытаюсь l oop через это

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'}
        ]
    },

]

и дело в том, что я хочу получить каждый вопрос с этим l oop и получить эти вопросы в журнале консоли

var currentQuestion = questions.length;

for( var i = 0; i < currentQuestion; i++){
   console.log(questions[i]);
}

но console.log сообщает: Uncaught TypeError: Невозможно прочитать свойство 'length' из неопределенного

Ответы [ 3 ]

1 голос
/ 02 мая 2020

Похоже, что переменные вопросы не включены в тот же файл.

0 голосов
/ 02 мая 2020

Использование для ..:

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);
 }
0 голосов
/ 02 мая 2020

больше информации на 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
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...