Javascript 作为参数的函数
方法checkAnswer无法传递参数keepScore。它安慰回调不是一个函数:我如何构造它,使第二个参数keepScore可以被checkAnswer使用Javascript 作为参数的函数,javascript,Javascript,方法checkAnswer无法传递参数keepScore。它安慰回调不是一个函数:我如何构造它,使第二个参数keepScore可以被checkAnswer使用 (function() { function Question(question, answers, correct) { this.question = question; this.answers = answers; this.correct = correct; } //Displa
(function() {
function Question(question, answers, correct) {
this.question = question;
this.answers = answers;
this.correct = correct;
}
//Display questions and answers
Question.prototype.displayQuestion = function() {
console.log(this.question);
for (let index = 0; index < this.answers.length; index++) {
console.log(index + ": " + this.answers[index]);
}
}
//Checking for correct answers
Question.prototype.checkAnwers = function(ans, callback) {
var sc;
if (ans === this.correct) {
console.log('Correct answer');
sc = callback(true);
} else {
console.log('Wrong answer')
sc = callback(false);
}
this.displayScore(sc);
}
//Display Scores to the console
Question.prototype.displayScore = function(score) {
console.log('Your current score is: ' + score);
console.log('---------------------------------');
}
//Populate questions, answers and correct answers
var q1 = new Question('Atom is the smallest particle of matter?', ['Yes', 'No'], 0);
var q2 = new Question('The element with atomic number of 16 is ?', ['silicon', 'sulphur', 'sodium'], 2);
var q3 = new Question('One of the easiest language to learn is ', ['Javascript', 'Python', 'Java'], 1);
var questions = [q1, q2, q3];
for (let index = 0; index < questions.length; index++) {
questions[index].displayQuestion();
var answer = prompt('Please enter the correct answer number');
if (answer === 'exit') {
break;
} else {
questions[index].checkAnwers(parseInt(answer), keepScore);
}
}
//Scoring the quiz
function score() {
var sc = 0;
return function(correct) {
if (correct) {
sc++;
}
return sc;
}
}
var keepScore = score();
})();
(函数(){
功能问题(问题、答案、正确){
这个问题=问题;
这个。答案=答案;
this.correct=正确;
}
//显示问题和答案
Question.prototype.displayQuestion=函数(){
console.log(这个问题);
for(让index=0;index代码中的问题是
var keepScore = score();
从不执行,因为for循环
,所以将核心
保留在checkAnswers
函数中未定义的位置
你得走了
var keepScore = score();
在循环之前
非常感谢。成功了。我通过在for循环之前调用它来移动它。