javascript isNaN() 与 parseInt() 混淆
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8271836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
isNaN() vs. parseInt() confusion
提问by Christophe Debove
There is something strange.
有什么奇怪的。
Why
with isNaN("")
I get False
But
with parseInt("")
I get NaN
?
为什么
与isNaN("")
我得到False
不过,
与parseInt("")
我得到NaN
?
回答by Ed Heal
isNaN
takes an integer as an argument - therefore JS converts ""
to 0
isNaN
接受一个整数作为参数 - 因此 JS 转换""
为0
parseInt
takes a string as an argument - therefore an empty string is not a number
parseInt
将字符串作为参数 - 因此空字符串不是数字
回答by Brian Nickel
This is because ""
is equivalent to zero in JavaScript. Try "" == 0
. This means if you try evaluating it in a numerical equation, it will come up as 0. When you parse it on the other hand it realizes there is nothing there.
这是因为""
在 JavaScript 中等于零。试试"" == 0
。这意味着如果您尝试在数值方程中对其进行评估,它将得出 0。另一方面,当您解析它时,它会意识到那里什么都没有。
As an alternative to parseInt
you could use Math.floor
. This will give you 0
for ""
.
作为替代,parseInt
您可以使用Math.floor
. 这会给你0
的""
。