Javascript Javascript 每日测试 - 第二期 0

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

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--

这里是《Javascript 每日测试 - 第二期》的 永久连接(Permalink),欢迎您 留言 或发送 Trackback。您也可以查看此篇文章的 Wap 版本(适用于移动设备)。 最后,如果您对本站的内容感兴趣,欢迎您 订阅本站
欢迎您留言

请输入您的称呼

请输入您的电子邮件

请您输入留言内容