【问题标题】:Javascript value returning not a number (NaN)返回非数字 (NaN) 的 Javascript 值
【发布时间】:2015-07-15 01:22:51
【问题描述】:

我有一段代码如下:

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

scoreguesses 在代码开头都设置为 0,并随着用户玩游戏而改变。代码可以正常工作,如果我离开 score 变量 0,我会得到一个 NaN 输出。 为什么我在score = 0 时得到 NaN 输出?

【问题讨论】:

标签: javascript variables nan


【解决方案1】:

代码可以正常工作,但如果我将分数变量设为 0,则会得到 NaN 输出。

您不应该这样做(来自 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

【讨论】:

  • 至少0/0 将返回NaN。其他任何 …/0…/-0 将返回 -InfinityInfinity,具体取决于两个数字的符号。
  • 哦,Infinity/Infinity 也会返回 NaN
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2020-06-04
    • 2015-11-26
    • 2016-03-01
    相关资源
    最近更新 更多