首页 > 解决方案 > 为什么 interate 函数首先打印而不是 randQuestion 函数打印?

问题描述

var Question = function(question, answer, correctAnswer) {
  this.question = question;
  this.answer = answer;
  this.correctAnswer = correctAnswer;
}

var quesArray = new Array();

quesArray.push(new Question('Is java script instresting?', ['yes', 'no', 'TBD'], 0));
quesArray.push(new Question('Who is the course teacher?', ['Mark', 'Jane', 'Jonas'], 3));
quesArray.push(new Question('What do u thing about codding? ', ['Fedup', 'Interesting', 'Okay'], 2));

function iterate(answer) {
  for (var i = 0; i < answer.length; i++) {
    console.log(answer[i]);
  }
}

function randQuestion() {
  var rand = 1 + Math.floor(Math.random()) * 2;
  var ques = quesArray[rand];
  console.log(ques.question + '\n' + iterate(ques.answer));
}
randQuestion();

输出:-

标记

乔纳斯脚本

课程老师是谁?

不明确的

-------------------------------------------------- -

我认为应该是什么?

课程老师是谁?

标记

乔纳斯脚本

标签: javascript

解决方案


iterate不返回任何东西。如果你想在

console.log(ques.question + '\n' + iterate(ques.answer));

那么你应该iterate返回一个字符串,可能joinanswer数组。

另一个问题是rand永远相等1。如果您想要一个真正随机的问题,请使用Math.floor(Math.random() * 3)

var Question = function (question, answer, correctAnswer) {
    this.question = question;
    this.answer = answer;
    this.correctAnswer = correctAnswer;
}

var quesArray = [];

quesArray.push(new Question('Is java script instresting?', ['yes', 'no', 'TBD'], 0));
quesArray.push(new Question('Who is the course teacher?', ['Mark', 'Jane', 'Jonas'], 3));
quesArray.push(new Question('What do u thing about codding? ', ['Fedup', 'Interesting', 'Okay'], 2));

function iterate(answer) {
  return answer.join('\n');
}

function randQuestion() {
    var rand = Math.floor(Math.random() * 3);
    var ques = quesArray[rand];
    console.log(ques.question + '\n' + iterate(ques.answer));
}
randQuestion();


推荐阅读