在JavaScript中,parseInt(字符串)和Number(字符串)之间的区别是什么?
当前回答
@sjngm回答的附录:
它们都忽略空白:
var foo = " 3 ";
console.log(parseInt(foo)); // 3
console.log(Number(foo)); // 3
其他回答
第一个函数有两个参数:
parseInt(string, radix)
radix参数用于指定要使用的数字系统,例如,基数16(十六进制)表示字符串中的数字应该从十六进制数解析为十进制数。
如果省略了radix参数,JavaScript假设如下:
如果字符串以“0x”开头,则 基数是16(十六进制) 如果字符串以“0”开头,则 基数是8(八进制)。这个特性 被弃用 如果字符串以任何其他开头 值,基数为10(十进制)
你提到的另一个函数只有一个参数:
Number(object)
Number()函数的作用是:将对象参数转换为表示对象值的数字。
如果该值不能转换为合法的数字,则返回NaN。
parseInt("123qwe")
返回123
Number("123qwe")
返回南
换句话说,parseInt()一直解析到第一个非数字,并返回它所解析的内容。Number()想要将整个字符串转换为一个数字,顺便说一句,这个数字也可以是一个浮点数。
编辑#1:Lucero评论了可以与parseInt()一起使用的基数。就这一点而言,请参阅下面医生的回答(我不打算在这里复制,医生应该有一个公平的份额…)
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 returns 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).
parseInt(string)将包含非数字字符的字符串转换为数字,只要字符串以数字字符开头
'10px' => 10
如果字符串包含任何非数字字符,Number(string)将返回NaN
'10px' => NaN
parseInt函数允许您为输入字符串指定基数,并且限制为整数值。
parseInt('Z', 36) === 35
作为函数调用的Number构造函数将使用语法解析字符串,并限制为以10为底和以16为底。
StringNumericLiteral ::: StrWhiteSpaceopt StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt StrWhiteSpace ::: StrWhiteSpaceChar StrWhiteSpaceopt StrWhiteSpaceChar ::: WhiteSpace LineTerminator StrNumericLiteral ::: StrDecimalLiteral HexIntegerLiteral StrDecimalLiteral ::: StrUnsignedDecimalLiteral + StrUnsignedDecimalLiteral - StrUnsignedDecimalLiteral StrUnsignedDecimalLiteral ::: Infinity DecimalDigits . DecimalDigitsopt ExponentPartopt . DecimalDigits ExponentPartopt DecimalDigits ExponentPartopt DecimalDigits ::: DecimalDigit DecimalDigits DecimalDigit DecimalDigit ::: one of 0 1 2 3 4 5 6 7 8 9 ExponentPart ::: ExponentIndicator SignedInteger ExponentIndicator ::: one of e E SignedInteger ::: DecimalDigits + DecimalDigits - DecimalDigits HexIntegerLiteral ::: 0x HexDigit 0X HexDigit HexIntegerLiteral HexDigit HexDigit ::: one of 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F
@sjngm回答的附录:
它们都忽略空白:
var foo = " 3 ";
console.log(parseInt(foo)); // 3
console.log(Number(foo)); // 3
推荐文章
- 在数组中获取所有选中的复选框
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类