是否可以在for循环中遍历length属性的条件语句?

时间:2018-10-15 18:18:41

标签: javascript arrays object for-loop iteration

感谢您抽出宝贵的时间对此进行研究。代码在下面。

let questions = [];

let Question = function(question, answers, number) {
    this.question = question;
    this.answers = answers;
    this.number = number;
}

let question1 = new Question('Is Javascript the best programming language?', 
['No', 'Yes'], 1);

let question2 = new Question('Is Javascript a web development language?', 
['No', 'Yes'], 1);

let question3 = new Question(`What is Javascript's official server side 
application called?`, ['BootStrap', 'Python', 'Node.js'], 2);

questions = [question1, question2, question3];

Question.randomQuestion = function() {
    let randomNum = Math.floor(Math.random() * 3);
    let randomQuestion = questions[randomNum];

    return randomQuestion;
}

Question.display = function(randomQuestion) {
    console.log(randomQuestion.question);
    debugger;
        // Why does the conditional give me undefined?
        for (let i = 0; i < questions[i].answers[i].length; i++)
        console.log(`${randomQuestion.answers[i]}`);    
    }

我想做的是在每次迭代中获得Answers属性的长度,但是我得到一个错误:答案是不确定的。为什么未定义,还有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

存在许多错误。基本上,当您遍历两个数组时,需要两个循环。 我已经用我的代码制作了此代码段,希望对您有所帮助:

let questions = [];

let Question = function (question, answers, number) {
  this.question = question;
  this.answers = answers;
  this.number = number;
}

let question1 = new Question('Is Javascript the best programming language?',
  ['No', 'Yes'], 1);

let question2 = new Question('Is Javascript a web development language?',
  ['No', 'Yes'], 1);

let question3 = new Question(`What is Javascript's official server side 
application called?`, ['BootStrap', 'Python', 'Node.js'], 2);

questions = [question1, question2, question3];

const randomQuestion = function () {
  let randomNum = Math.floor(Math.random() * 3);
  let randomQuestion = questions[randomNum];
  return randomQuestion;
}

const display = function (randomQuestion) {
  const random_question = randomQuestion();
  console.log(random_question.question);
  //debugger;
  // Why does the conditional give me undefined?
  //dump all question and all answers
  for (let i = 0; i < questions.length; i++)
    for (let j = 0; j < questions[i].answers.length; j++)
      console.log(`${questions[i].answers[j]}`);
  //as an alternative :
  questions.forEach(e => {
    console.log(e.question);
    e.answers.forEach(a => {
      console.log(a)
    })
  })
}

display(randomQuestion);