parseInt的主要作用是把字符串轉(zhuǎn)換為整數(shù),或者把小數(shù)轉(zhuǎn)換為整數(shù)。一般情況下,我們只用到它的第一個參數(shù)。但實際上,它有兩個參數(shù):
parseInt(string, radix)
parseInt會根據(jù)radix指定的進制進行轉(zhuǎn)換,比如:
代碼如下:
alert(parseInt("10", 2)); // outputs '2'
在沒有指定radix或者radix為0的情況下,parseInt會按十進制進行轉(zhuǎn)換。然而,這在某些情況下有點特殊:
* 如果string的值以“0x”開頭,parseInt會按十六進制進行轉(zhuǎn)換;
* 如果string的值以“0”開頭,parseInt會按八進制進行轉(zhuǎn)換。
說回開頭的代碼,由于"09"是以“0”開頭,所以parseInt會按八進制進行轉(zhuǎn)換,但是“9”不是合法的八進制值(八進制只有0-7八個數(shù)字),所以轉(zhuǎn)換結果是0。
要避免這個陷進,可以強制指定radix:
代碼如下:
alert(parseInt("09", 10)); // outputs '9'
其它網(wǎng)友的補充:
看代碼:
代碼如下:
alert(parseInt(0.000001));
alert(parseInt(0.0000001));
第一條語句輸出 0, 第二條語句輸出 1, 囧。
繼續(xù)看代碼:
代碼如下:
alert(parseInt('0.000001'));
alert(parseInt('0.0000001'));
都輸出 0, 這才符合預期。
查看 ECMA-262 規(guī)范,parseInt 會先調(diào)用 toString 方法。問題已逐漸清晰:
代碼如下:
alert(0.000001);
alert(0.0000001);
第一條語句原樣輸出,第二條語句輸出 1e-7.
繼續(xù)翻查 ECMA-262 9.8.1 ToString Applied to the Number Type 一節(jié),恍然大悟:
代碼如下:
assertEquals("0.00001", (0.00001).toString());
assertEquals("0.000001", (0.000001).toString());
assertEquals("1e-7", (0.0000001).toString());
assertEquals("1.2e-7", (0.00000012).toString());
assertEquals("1.23e-7", (0.000000123).toString());
assertEquals("1e-8", (0.00000001).toString());
assertEquals("1.2e-8", (0.000000012).toString());
上面是 V8 引擎 number-tostring 的單元測試腳本, 很好地詮釋了 ECMA 規(guī)范。
小結:對于小于 1e-6 的數(shù)值來說,ToString 時會自動轉(zhuǎn)換為科學計數(shù)法。因此 parseInt 方法,在參數(shù)類型不確定時,最好封裝一層:
代碼如下:
function parseInt2(a) {
if(typeof a === 'number') {
return Math.floor(a);
}
return parseInt(a);
}
blueidea上面的文章:
去年11月做的一個東西,到今年 8,9 月突然出毛病了
調(diào)試了 1x 分鐘最后發(fā)現(xiàn)是 parseInt 的問題
MSDN 里的說明
Description
Converts strings into integers.
Syntax
parseInt(numstring, [radix])
The parseInt method syntax has these parts:
Part Description
[numstring] Required. A string to convert into a number.
[radix] Optional. A value between 2 and 36 indicating the base of the number contained in numstring. If not supplied, strings with a prefix of '0x' are considered hexidecimal and strings with a prefix of '0' are considered octal. All other strings are considered decimal.
用 parseInt 是在日期上的,比如 2005-10-08 用 正則解出 年月日 字符串,再用parseInt解出數(shù)字做他用。