gpt4 book ai didi

javascript - 为什么 Number ('' ) 返回 0 而 parseInt ('' ) 返回 NaN

转载 作者:数据小太阳 更新时间:2023-10-29 04:18:04 24 4
gpt4 key购买 nike

我在 StackOverflow 上浏览了类似的问题和答案,发现了这个:

parseInt("123hui")
returns 123

Number("123hui")
returns NaN

作为,parseInt()解析到第一个非数字并返回它解析的任何内容和Number()尝试将整个字符串转换为数字,为什么在 parseInt('') 的情况下不太可能出现这种行为?和 Number('') .

我感觉很理想parseInt应该返回 NaN就像它对 Number("123hui") 所做的一样

现在我的下一个问题:

作为0 == ''返回 true我相信它解释为 0 == Number('')这是真的。那么编译器真的像0 == Number('')一样对待它吗?而不像0 == parseInt('')还是我遗漏了一些要点?

最佳答案

差异部分是由于 Number() 使用了额外的类型强制逻辑。包含在 the rules it follows 中这是:

  • A StringNumericLiteral that is empty or contains only white space is converted to +0.

parseInt()被定义为根据给定或检测到的 radix 简单地查找和评估输入中的数字字符。并且,它被定义为需要至少一个有效字符。

13) If S contains a code unit that is not a radix-R digit, let Z be the substring of S consisting of all code units before the first such code unit; otherwise, let Z be S.

14) If Z is empty, return NaN.

注意:'S' 是删除所有前导空格后的输入字符串。


As 0=='' returns true I believe it interprets like 0==Number('') [...]

== 使用的规则定义为 Abstract Equality .

而且,您对所使用的强制转换/转换是正确的。相关步骤是#6:

If Type(x) is Number and Type(y) is String,
return the result of the comparison x == ToNumber(y).

关于javascript - 为什么 Number ('' ) 返回 0 而 parseInt ('' ) 返回 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34282371/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com