关于"parseInt"
来源:互联网 发布:鞋子进销存软件 编辑:程序博客网 时间:2024/05/17 09:13
在进行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)进行转换就没有问题了.
- 关于"parseInt"
- 关于parseInt
- 关于javascript中的parseInt
- 关于javascript parseInt函数
- 关于JavaScript parseInt() 函数
- 关于js 中parseInt
- 关于Integer.parseInt
- 关于JS函数parseInt()说明
- 关于js的parseInt() 函数
- parseInt()
- parseInt()
- parseInt()
- parseInt()
- ParseInt
- parseInt()
- parseInt
- ParseInt
- parseInt()
- 加密技术
- 看了一下MD5加密算法的介绍,然后顺手把C实现改成了个C++类
- 免费的桌面主题按钮 V1.0
- 紫光华宇拼音输入法V6 beta 3
- 7-Zip 4.52 Beta简体中文版
- 关于"parseInt"
- 自动排课系统V2.0基本完善了
- 浅谈Object Pascal的指针
- COM与DCOM的区别与联系
- 对Object Pascal编译器给类对象分配堆内存细节的一种大胆猜测
- CPU信息的获得
- 数据库中的图象存取
- 针对构架师的.NET 3.0介绍
- 浅谈C/C++内存泄漏及其检测工具