parseInt('1'); // 1
parseInt('1.2'); // 1
parseInt('-1.2'); // -1
parseInt(1.2); // 1 (隱式轉字串)
parseInt(0); // 0
parseInt('0'); // 0
parseInt('06'); // 6 ✅ (現代瀏覽器)
parseInt('08'); // 0 ❌ (舊版視為八進制,8 非法字元導致解析停止)
parseInt('09'); // 0 ❌
parseInt('1g'); // 1 (忽略非數字後綴)
parseInt('g1'); // NaN (首字元非數字)
現代瀏覽器(ES5+)預設十進制,不再自動識別八進制,但為了相容與明確,永遠指定基數:
parseInt('08', 10); // 8 ✅
parseInt('0xFF', 16); // 255
function toInt(number) {
return number * 1 | 0 || 0;
}
// 測試
toInt('1'); // 1
toInt('1.2'); // 1
toInt('-1.2'); // -1
toInt(1.2); // 1
toInt(0); // 0
toInt('0'); // 0
toInt(NaN); // 0
toInt(Infinity); // 0
toInt('abc'); // 0
原理:| 0 強制轉 32 位有號整數,|| 0 處理 NaN/Infinity。
function toInt(number) {
return number && +number | 0 || 0;
}
// number 為 0、null、undefined、'' 時短路回傳 0
function toInt(number) {
return Infinity === number ? 0 : (Number(number) || 0).toFixed(0) * 1;
}
// 注意:JS 安全整數範圍 -2^53 ~ 2^53,超出仍會失真
// 基準測試(百萬次迴圈)
console.time('parseInt');
for (var i=0; i<1e6; i++) parseInt('123.45', 10);
console.timeEnd('parseInt'); // ~45ms
console.time('toInt-bitwise');
for (var i=0; i<1e6; i++) toInt('123.45');
console.timeEnd('toInt-bitwise'); // ~12ms (快 3-4 倍)
console.time('Math.floor');
for (var i=0; i<1e6; i++) Math.floor(123.45);
console.timeEnd('Math.floor'); // ~15ms
| 方法 | 1.2 | -1.2 | '1.2' | 'abc' | NaN | Infinity | 備註 |
|---|---|---|---|---|---|---|---|
| parseInt(x, 10) | 1 | -1 | 1 | NaN | NaN | NaN | 標準、可指定基數 |
| Number(x) | 0 | 1 | -1 | 1 | 0 | 0 | 0 | 快、32位截斷 |
| Math.floor(x) | 1 | -2 | 1 | NaN | NaN | Infinity | 向下取整(負數不同) |
| Math.trunc(x) | 1 | -1 | 1 | NaN | NaN | Infinity | ES6、直接截斷小數 |
| ~~x | 1 | -1 | 1 | 0 | 0 | 0 | 雙重位非運算、極快 |
| x >> 0 | 1 | -1 | 1 | 0 | 0 | 0 | 有號右移 0 位 |
parseInt(str, 10) —— 語意明確、可讀性最好num | 0 或 ~~num —— 遊戲迴圈、動畫幀計算Math.floor()(正數)/ Math.trunc()(ES6、負數同向截斷)toInt() 處理邊界情況parseInt 是語意最清晰的選擇,但永遠指定基數 10。高效能場景用位運算 | 0。理解各方法對負數、NaN、Infinity、非數字字串的處理差異,根據場景選擇最適合的工具。