JS在尝试向变量添加数字时接收NaN

时间:2017-10-24 23:58:51

标签: javascript

我正在尝试编写掷骰子游戏,但我不断在我的控制台中获得一个NaN号码。

    var dice, score;

function rollDice() {

  dice = Math.floor((Math.random() * 6) + 1);
  dice !== 1 ? score += dice : score = 0;

  return score;
}

var hey = rollDice();
console.log(hey); 

3 个答案:

答案 0 :(得分:1)

您需要为score变量分配默认值,例如score = 0,因为它现在未定义。示例:JSFiddle

答案 1 :(得分:0)

您的变量score永远不会初始化为某个值,因此执行此操作时:

score += dice

它确实在表现:

undefined += 3

undefined +一个数字始终是NaN。 尝试初始化score0

var dice = 0;
var score = 0;



var dice = 0;
var score = 0;

function rollDice() {

  dice = Math.floor((Math.random() * 6) + 1);
  dice !== 1 ? score += dice : score = 0;

  return score;
}

var hey = rollDice();
console.log(hey); 




答案 2 :(得分:-1)

你的三元是导致NaN的原因。试试这个。

score = dice !== 1 ? (dice + 1) : 0;

示例:https://repl.it/NKul/1

修改

修正了三元的真实条件。