在JavaScript中,parseInt(string)
和Number(string)
有什么不同?
在JavaScript中,parseInt(string)
和Number(string)
有什么不同?
parseInt("123qwe")
返回123
Number("123qwe")
返回NaN
换句话说,parseInt()
解析到第一个非数字,并返回它解析的内容.Number()
希望将整个字符串转换为数字,顺便说一句,数字也可以是浮点.
编辑#1:Lucero comments 了可以与parseInt()
一起使用的基数.关于这一点,请看下面的THE DOCTOR's answer条(我不打算在这里复制,doctor 应该有一个公平的声誉份额…).
EDIT #2: Regarding use cases: That's somewhat written between the lines already. Use Number()
in cases where you indirectly want to check if the given string completely represents a numeric value, float or integer. parseInt()/parseFloat()
aren't that strict as they just parse along and stop when the numeric value stops (radix!), which makes it useful when you need a numeric value at the front "in case there is one" (note that parseInt("hui")
also 返回NaN
). And the biggest difference is the use of radix that Number()
doesn't know of and parseInt()
may indirectly guess from the given string (that can cause weird results sometimes).