Javascript 返回的值不是数字 (NaN)

Javascript value returning not a number (NaN)

我有一段代码如下:

var percentageTemp =((parseInt(score)/parseInt(guesses))*100);
var percentage= percentageTemp.toFixed(2);

scoreguesses 在代码的开头都设置为 0,并随着用户玩游戏而改变。该代码按预期工作,如果我将 score 变量保留为 0,我会得到一个 NaN 输出。 为什么我在 score = 0 时得到 NaN 输出?

The code works as it should, exept if I leave score variable 0, I get a NaN output.

你不应该这样做(来自 Node.JS REPL 的示例):

> var score = 0; var guesses = 1; var percentageTemp =((parseInt(score)/parseInt(guesses))*100); var percentage= percentageTemp.toFixed(2); console.log(percentage)
0.00

另一方面,如果您将 guesses 留在 0,那么:

> var score = 0; var guesses = 0; var percentageTemp =((parseInt(score)/parseInt(guesses))*100); var percentage= percentageTemp.toFixed(2); console.log(percentage)
NaN

... 因为 it isn't possible to divide by zero

我建议使用基数。 parseInt(score, 10) 以确保该值不会转换为十六进制。另外,请注意 javascripts 处理十进制数是不准确的。尝试将其放入您的控制台 - (0.1 + 0.2) 并查看返回的异常值 - 0.30000000000000004