关于"parseInt"

在进行js脚本编写的时候,parseInt这个函数经常被使用,
目的是将 一个字符串转换为整型数.但是这个函数的实现和我们一般的想象有一定的差距.如:

我们用 parseInt('08'),希望得到的是 8,结果得到的是 0  (特别是在日期转换中)

在js帮助中有这样一段:
parseInt( ) parses and returns the first number (with an optional leading minus sign) that occurs in s. Parsing stops, and the value is returned, when parseInt( ) encounters a character in s that is not a valid digit for the specified radix. If s does not begin with a number that parseInt( ) can parse, the function returns the not-a-number value NaN. Use the isNaN( ) function to test for this return value.

The radix argument specifies the base of the number to be parsed. Specifying 10 makes parseInt( ) parse a decimal number. The value 8 specifies that an octal number (using digits 0 through 7) is to be parsed. The value 16 specifies a hexadecimal value, using digits 0 through 9 and letters A through F. radix can be any value between 2 and 36.

If radix is 0 or is not specified, parseInt( ) TRies to determine the radix of the number from s. If s begins (after an optional minus sign) with 0x, parseInt( ) parses the remainder of s as a hexadecimal number. If s begins with a 0, the ECMAScript v3 standard allows an implementation of parseInt( ) to interpret the following characters as an octal number or as a decimal number. Otherwise, if s begins with a digit from 1 through 9, parseInt( ) parses it as a decimal number.


所以 parseInt对于 0开头的字符串,且不是0x,当作了八进制进行处理,碰到8,就当作是非法字符中断了处理,所以结果就是0.

因此,在日期处理上,只有碰到 08,09,才会出现问题,所以大多数人很难不查文档很难发觉.

那应该怎么办呢?其实js提供了一个重载函数来解决这个问题
parseInt(s, radix)

radix

An optional integer argument that represents the radix (i.e., base) of the number to be parsed. If this argument is omitted or is 0, the number is parsed in base 10or in base 16 if it begins with 0x or 0X. If this argument is less than 2 or greater than 36, parseInt( ) returns NaN.

我们可以用 parseInt( '08',10)进行转换就没有问题了. 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值