任务
构建一个名为Question的函数构造函数来描述一个问题。一个问题应该包括: a)质疑自己 b)玩家可以选择正确答案的答案(在这里选择适当的数据结构,数组,对象等) c)正确答案(我会使用一个数字)
使用constructr
我的问题:我试图通过问题本身和问题1或问题2等对象使用问题构造函数的方法,但在输出中只是错误:
Question.randomQuestion不是函数
我的解决方案:
function Question(question, answers, correctAnswer) {
this.question = question;
this.answers = answers;
this.correctAnswer = correctAnswer;
}
Question.prototype.randomQuestion = function(questions) {
// random number for list
var randomQuestion = Math.floor(Math.random() * questions.length) + 1;
console.log(questions[randomQuestion].question)
// output answers for random question
for(var i = 0; i < questions[randomQuestion].answers.length; i++) {
console.log(questions[randomQuestion].answers[i]);
}
return questions[randomQuestion];
};
Question.prototype.checkCorrectAnswerOfUser = function(currentObject, choiceOfUser) {
if (choiceOfUser === currentObject.correctAnswer) console.log('Correct answer!');
else console.log("I'm sorry, but your answer is wrong...");
};
// pass our questions
var question1 = new Question('Is JavaScript the best programming language?', ['Yes', 'No', "I Don't know"], 0);
var question2 = new Question('Who is Daniil?', ['cloudy man', 'cloudy girl'], 0);
var question3 = new Question('Who is Alin?', ['programmer', 'designer', 'photograph'], 2);
// make the array of questions
var listOfQuestions = [question1, question2, question3];
// save point to the current object in variable
var currentObject = Question.randomQuestion(listOfQuestions);
var choiceOfUser = prompt('Please select the correct answer. (Just type of number)');
答案 0 :(得分:0)
将Question.prototype.randomQuestion
更改为:Question.randomQuestion
答案 1 :(得分:0)
在第4步中,作业有点误导:
选择随机问题并将其记录在控制台上,连同可能的答案(每个问题都应该有一个数字)(提示:为此任务的Question对象编写方法)。
实际上这是两项任务:
您应该为此编写两个单独的程序。第一个(可以推广到任意数组,不仅仅是那个特定的问题数组)应该是一个简单的全局函数:
function getRandomElement(array) {
…
return element;
}
只有第二个实际上应该是一个问题的方法:
Question.prototype.display = function() {
… // use `this` to refer to the instance
};
您可以将其称为currentQuestion.display()
。