代码改变世界

JavaScript_Funny ParseInt

2010-03-13 22:52  蜡笔小旧  阅读(170)  评论(0编辑  收藏  举报
1 var num1 = "01"//1
2 var num7 = "07"//7
3 var num8 = "08"//0
4 var num9 = "09"//0
5 var num10 = "010"//8
6 alert( parseInt(d) ); 

 为什么会这样子?

 看看parseInt这个函数:

parseInt(string, radix) 

ParameterDescription
stringRequired. The string to be parsed
radixOptional. A number (from 2 to 36) that represents the numeral system to be used

 If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with "0x", the radix is 16 (hexadecimal)
  • If the string begins with "0", the radix is 8 (octal). This feature is deprecated
  • If the string begins with any other value, the radix is 10 (decimal)

Tips and Notes

Note: Only the first number in the string is returned!

Note: Leading and trailing spaces are allowed.

Note: If the first character cannot be converted to a number, parseInt() returns NaN.


 

Browser 认为字符串第一个字符带0就是八进制数值,八进制也只有0~7。 parseInt(d, 10)就Ok了。