javascript - 为什么 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();
输出:-
标记
简
乔纳斯脚本
课程老师是谁?
不明确的
-------------------------------------------------- -
我认为应该是什么?
课程老师是谁?
标记
简
乔纳斯脚本
解决方案
iterate
不返回任何东西。如果你想在
console.log(ques.question + '\n' + iterate(ques.answer));
那么你应该iterate
返回一个字符串,可能join
是answer
数组。
另一个问题是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();
推荐阅读
- api - 如何使“授权集群端点”功能,为 Rancher 创建的集群启用默认值,可用于在 Rancher 中导入的现有集群
- lauterbach - 如何为测试操作系统编写操作系统感知 t32 配置
- java - 如何将openshift中的POD日志获取到本地文件
- javascript - 当其他计算按预期工作时,为什么其中一个计算返回 NaN?
- aurelia - Aurelia:无法识别功能模块
- c# - 交叉应用两个列表,返回相同的修改对象
- linux - 如果存在另一行,则 Bash 替换行
- c# - ASP.Net Core - 配置管理器不从 Web.config 加载数据
- sql - 获取前九行,然后得到第十行以及其他所有内容的总和
- c# - asp.net core webapi中出现反序列化异常时如何停止验证调用