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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:52:05  来源:igfitidea点击:

isNaN() vs. parseInt() confusion

javascript

提问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

isNaNtakes an integer as an argument - therefore JS converts ""to 0

isNaN接受一个整数作为参数 - 因此 JS 转换""0

parseInttakes 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 parseIntyou could use Math.floor. This will give you 0for "".

作为替代,parseInt您可以使用Math.floor. 这会给你0""