javascript - 在 Javascript 中将 NaN 更改为 0

标签 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 to NaN, but aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true.

比较:

isNaN("a"); // true
Number.isNaN("a"); // false

关于javascript - 在 Javascript 中将 NaN 更改为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21604215/

相关文章:

javascript - 在 Django 中用另一个字段值动态更新字段

javascript - 在 Vue 应用程序中粘贴大内容时,Quill 编辑器会稍微向上滚动

javascript - 绑定(bind) jquery 数据表给出错误 "Requested unknown parameter ' 0' from the data source for row 0"

php - 使用 Ajax 和 MySql 分离结构

javascript - 没有重复的服务器端事件

javascript - Chrome 和 Windows 的非最佳 WebGL 性能

java - 自定义对话框执行 NPE

javascript - Protractor :对元素集合使用 where 子句

javascript - 在调整大小和浏览器宽度时触发 jQuery

JavaScript 围绕特定点旋转 SVG 对象 `transform: rotate()`