有没有一种方法将NaN值转换为0而不使用if语句?例子:

if (isNaN(a)) a = 0;

每次检查我的变量都很烦人。


当前回答

如果您试图使用parseInt(),则使用isNaN的方法将不起作用。例如,

parseInt("abc"); // NaN
parseInt(""); // NaN
parseInt("14px"); // 14

但在第二种情况下,isNaN产生false(即,空字符串是一个数字)。

n="abc"; isNaN(n) ? 0 : parseInt(n); // 0
n=""; isNaN(n) ? 0: parseInt(n); // NaN
n="14px"; isNaN(n) ? 0 : parseInt(n); // 14

总而言之,空字符串被isNaN视为有效数字,而不是parseInt()。它已在macOS v10.14 (Mojave)上的Safari, Firefox和Chrome上进行了验证。

其他回答

请试试这个简单的功能

var NanValue = function (entry) {
    if(entry=="NaN") {
        return 0.00;
    } else {
        return entry;
    }
}

对任何事情都更简单有效的方法:

function getNum(val) {
   val = +val || 0
   return val;
}

...这将把a从任何“假”值转换为0。

“伪”值是:

假 零 未定义的 0 ""(空字符串) NaN(非数字)

与其拼凑它以便您可以继续,为什么不备份并想知道为什么您首先会遇到NaN呢?

如果操作的任何数字输入是NaN,则输出也将是NaN。这就是当前IEEE浮点标准的工作方式(不仅仅是Javascript)。这种行为有一个很好的理由:潜在的意图是防止您使用虚假的结果,而没有意识到它是虚假的。

NaN的工作方式是,如果在某个子-子-子操作中出现错误(在较低的级别产生NaN),最终结果也将是NaN,即使您的错误处理逻辑(可能是throw/catch ?)还没有完成,您也会立即将其识别为错误。

NaN作为算术计算的结果总是表明在算术的细节中出现了错误。这是计算机表示“这里需要调试”的一种方式。与其想方设法继续处理一些几乎不正确的数字(你真的想要0吗?),为什么不找到问题并解决它呢?

A common problem in Javascript is that both parseInt(...) and parseFloat(...) will return NaN if given a nonsensical argument (null, '', etc). Fix the issue at the lowest level possible rather than at a higher level. Then the result of the overall calculation has a good chance of making sense, and you're not substituting some magic number (0 or 1 or whatever) for the result of the entire calculation. (The trick of (parseInt(foo.value) || 0) works only for sums, not products - for products you want the default value to be 1 rather than 0, but not if the specified value really is 0.)

也许为了编码方便,你想要一个函数从用户那里检索一个值,清理它,并在必要时提供一个默认值,就像这样:

function getFoobarFromUser(elementid) {
        var foobar = parseFloat(document.getElementById(elementid).innerHTML)
        if (isNaN(foobar)) foobar = 3.21;       // default value
        return(foobar.toFixed(2));
}

使用双波浪号(双位NOT) - ~~ -在JavaScript中做了一些有趣的事情。例如,你可以用它来代替数学。floor或甚至作为parseInt("123", 10)的替代!在网络上已经讨论过很多次了,所以我不会在这里解释为什么它可以工作,但如果你感兴趣的话:JavaScript中的“双波浪号”(~~)操作符是什么?

我们可以利用双波浪号的这个属性将NaN转换为一个数字,幸运的是,这个数字是零!

console.log(~~NaN);0

var i = [NaN, 1,2,3]; var j = i.map(i =>{返回isNaN(i) ?0: i}); console.log (j)