<分区>
我有一个代码可以在引导模式中返回 javascript 平均函数的结果。但是当其中一个输入为空时,他返回 NaN 。我如何将 NaN 更改为 0?
这是我返回结果的代码:
$(".average").click(function () {
var result = average();
$("#myModal .modal-body h2").text(result);
$("#myModal").modal();
});
标签 javascript
<分区>
我有一个代码可以在引导模式中返回 javascript 平均函数的结果。但是当其中一个输入为空时,他返回 NaN 。我如何将 NaN 更改为 0?
这是我返回结果的代码:
$(".average").click(function () {
var result = average();
$("#myModal .modal-body h2").text(result);
$("#myModal").modal();
});
最佳答案
您可以使用 isNaN
检查值是否为 NaN
功能:
var result = average();
if (isNaN(result)) result = 0;
将来,当 ECMAScript 6 广泛可用时,您可能会考虑切换到 Number.isNaN
,因为 isNaN
没有正确处理字符串作为参数。
In comparison to the global
isNaN
function,Number.isNaN
doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert toNaN
, but aren't actually the same value asNaN
. This also means that only values of the typenumber
, that are alsoNaN
, returntrue
.
比较:
isNaN("a"); // true
Number.isNaN("a"); // false
关于javascript - 在 Javascript 中将 NaN 更改为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21604215/