JavaScript函数返回NaN,即使value是一个数字

时间:2017-11-07 16:12:04

标签: javascript function

我正在开设课程作业,其中随机问题被提出,每个问题有4个可能的答案。 (这只在控制台中运行,与alert()一起使用)。

我的问题在于用户的得分。它应该在每次正确迭代时递增1并且我尝试使用函数解析它,但函数返回NaN并且我根本看不到问题。请看看。

//Start by creating objects to contain the questions and answers
var Questions = function(question, answerq1, answerq2, answerq3, answerq4) {
  this.question = question;
  this.answerq1 = answerq1;
  this.answerq2 = answerq2;
  this.answerq3 = answerq3;
  this.answerq4 = answerq4;
};

//create the questions 
var question1 = new Questions('What is the fastest land animal in the world?', 'a dog', 'deer', 'cheetah', 'leopard');

//create a function that displays the question and present the possible answers as multiple option
function displayQandA() {
  var test = 'question' + 1;
  console.log(test);
  if (test === 'question1') {
    console.log(question1.question);
    var q10a = [question1.answerq1, question1.answerq2, question1.answerq3, question1.answerq4];
    //correct answer in array
    var correct = q10a[2];
    for (var i = 0; i < q10a.length; i++) {
      console.log([i] + ' ' + q10a[i]);
    }
    captureAnswer(q10a.indexOf(correct));
  } else {
    displayQandA();
  }
};
displayQandA();

//to hold score accumulation
var s = 0;
//function to increase score per correct answer        
function incrementScore() {
  s++;
  return s;
};

//function to prompt user to enter/capture the answer & check whether its correct or not
function captureAnswer(el) { //el is the parameter from the random question function
  var promptAnswer = prompt('Capture your answer here');

  if (promptAnswer === 'exit') {
    console.log('You entered ' + promptAnswer);
    console.log('Bye, thanks for playing');
  } else if (promptAnswer == el) {
    console.log('You entered ' + promptAnswer);
    console.log('Your answer is correct!');
    incrementScore();
    console.log('Your score is ' + s);
    displayQandA(); //calling random question function
  } else if (promptAnswer !== el) {
    console.log('You entered ' + promptAnswer);
    console.log('Your answer is wrong!');
    console.log('Your score remains ' + s);
    displayQandA(); //calling random question function
  }
};

3 个答案:

答案 0 :(得分:0)

这是因为您在分配displayQandA之前致电s = 0。该函数已经读取s(产生undefined)并递增它(产生NaN)。 var s;已被提升,因此它将以undefined开头。实际上,只有在提示符中键入s = 0;后才会执行"exit"。只需将var s = 0;移到代码顶部即可。

答案 1 :(得分:-1)

使用parseInt()对变量进行类型转换,比较运算符(!==)检查类型或值差异。

答案 2 :(得分:-1)

= +与+ =不同。首先是x = + y,另一个是x = x + y。

+ x是Number(x)字面上将变量转换为数字的快捷方式。如果无法执行操作,则返回NaN。

当其中一个部分(左或右)具有字符串类型时,

+ =就像字符串连接一样。