在javascript中将NaN转换为0 [英] Convert NaN to 0 in javascript
问题描述
有没有办法在没有if语句的情况下将NaN值转换为0:
Is there a way to convert NaN values to 0 without an if statement:
if (isNaN(a)) a = 0;
每次检查变量都非常烦人。
It is very annoying to check my variables every time.
推荐答案
你可以这样做:
a = a || 0
...将a从任何falsey值转换为 0
。
...which will convert a from any "falsey" value to 0
.
假值为:
-
false
-
null
-
undefined
-
0
-
(空字符串)
-
NaN
(非数字)
false
null
undefined
0
""
( empty string )NaN
( Not a Number )
如果您愿意,可以这样:
Or this if you prefer:
a = a ? a : 0;
...具有与上述相同的效果。
...which will have the same effect as above.
如果目的是测试的不仅仅是 NaN
,那么你也可以这样做,但是首先进行 toNumber 转换。
If the intent was to test for more than just NaN
, then you can do the same, but do a toNumber conversion first.
a = +a || 0
这使用一元+运算符来尝试转换 a
到一个数字。这样可以将数字字符串'123'
等内容转换为数字。
This uses the unary + operator to try to convert a
to a number. This has the added benefit of converting things like numeric strings '123'
to a number.
唯一出乎意料的事情可能是有人通过可以成功转换为数字的数组:
The only unexpected thing may be if someone passes an Array that can successfully be converted to a number:
+['123'] // 123
这里我们有一个Array,它有一个数字字符串成员。它将成功转换为数字。
Here we have an Array that has a single member that is a numeric string. It will be successfully converted to a number.
这篇关于在javascript中将NaN转换为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!