$Frank$

沙漠绿洲,感受生活..

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
发现javascript中的parseInt函数的一个"bug":
parseInt("07") = 7
parseInt("08") = 0
parseInt("09") = 0

原因:
原来当前面有0的时候,parseInt默认把它当作八进制处理了,01--07自然没有问题。
但是09,08都是不合格的八进制形式,所以被按照0处理了。

解决方案:

利用parseInt函数的另一个参数,显示指定parseInt按十进制处理。
例如:
parseInt("08",10) =8
parseInt("09",10) =9

问题解决!


附录:


parseInt

Parses a string argument and returns an integer of the specified radix or base.

核心函数
实现版本 Navigator 2.0: If the first character of the string specified in parseInt(string) cannot be converted to a number, returns "NaN" on Solaris and Irix and 0 on all other platforms.Navigator 3.0, LiveWire 2.0: Returns "NaN" on all platforms if the first character of the string specified in parseInt(string) cannot be converted to a number.

语法

parseInt(string,radix)

参数

string A string that represents the value you want to parse.
radix (Optional) An integer that represents the radix of the return value.

描述

The parseInt function is a built-in JavaScript function.

The parseInt function parses its first argument, a string, and attempts to return an integer of the specified radix (base). For example, a radix of 10 indicates to convert to a decimal number, 8 octal, 16 hexadecimal, and so on. For radixes above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values.

If the radix is not specified or is specified as 0, JavaScript assumes the following:

If the first character cannot be converted to a number, parseInt returns "NaN".

For arithmetic purposes, the "NaN" value is not a number in any radix. You can call the isNaN function to determine if the result of parseInt is "NaN". If "NaN" is passed on to arithmetic operations, the operation results will also be "NaN".

示例

The following examples all return 15:
parseInt("F", 16)
parseInt("17", 8)
parseInt("15", 10)
parseInt(15.99, 10)
parseInt("FXX123", 16)
parseInt("1111", 2)
parseInt("15*3", 10)


The following examples all return "NaN":
parseInt("Hello", 8)
parseInt("0x7", 10)
parseInt("FFF", 10)


Even though the radix is specified differently, the following examples all return 17 because the input string begins with "0x".
parseInt("0x11", 16)
parseInt("0x11", 0)
parseInt("0x11")

参看

isNaN, parseFloat, Object.valueOf
posted on 2007-01-02 17:24  Frank.Sharp  阅读(842)  评论(0)    收藏  举报