这回是 小马 同学出的题目:

var a = parseInt('01');
alert(a == 1); //true
var b = parseInt('09/04/2008');
alert(b == 9); //?

请问第二个会弹出 true 还是 false ?

首先是 沈冲 同学的回答:

如果 string 以 0 开头,那么 ECMAScript v3 允许 parseInt() 的一个实现
把其后的字符解析为八进制或十六进制的数字。

佩玉 同学就更牛了,直接转贴了 Javascript 犀牛书上的内容:

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.

总结,parseInt 其实有两个参数( 详细 ):

parseInt(string[, radix])

所以当第一个参数遇到 0 开头的字符时,会自动使用 8 进制解析数字,而 9 不是 8 进制里合法的数字,所以返回 0 。所以要在 parseInt 函数中数指定进制(也就是第二个参数),才能得到期望的结果。

为了代码的健壮性,建议使用 parseInt 时总是指定第二个参数 -- 小马。

--EOF--