字串轉數值是前端高頻操作,但 JavaScript 的型別轉換行為充滿陷阱。本文系統比較 5 種轉換方法的行為差異、效能、邊界情況,提供生產環境可用的最佳實踐模式。
| 方法 | 語法 | "42" | "3.14" | " 42 " | "42px" | "" | null | undefined | NaN行為 |
|---|---|---|---|---|---|---|---|---|---|
| parseInt | parseInt(str, 10) | 42 | 3 | 42 | 42 | NaN | NaN | NaN | 返回 NaN |
| parseFloat | parseFloat(str) | 42 | 3.14 | 42 | 42 | NaN | NaN | NaN | 返回 NaN |
| Number() | Number(str) | 42 | 3.14 | 42 | NaN | 0 | 0 | NaN | 返回 NaN |
| 一元加號 | +str | 42 | 3.14 | 42 | NaN | 0 | 0 | NaN | 返回 NaN |
| 位元運算 | str | 0 | 42 | 3 | 42 | 0 | 0 | 0 | 0 | 返回 0 |
// 關鍵:永遠指定基數 10,避免八進制誤判
parseInt('42', 10); // 42
parseInt('042', 10); // 42 (非八進制)
parseInt('0xFF', 10); // 0 (停止於 x)
parseInt('0xFF', 16); // 255 (十六進制)
// 解析規則:跳過前導空白 → 讀取符號 → 讀取數字字元 → 遇非數字停止
parseInt(' -42px', 10); // -42
parseInt('abc', 10); // NaN
// 進制自動檢測 (不指定 radix 時)
parseInt('0xFF'); // 255 (ES5+ 標準化,不再視為八進制)
parseInt('077'); // 77 (ES5+ 十進制,舊版可能視為八進制 63)
// 嚴格模式:任何非數字字元導致 NaN
Number('42'); // 42
Number('3.14'); // 3.14
Number('42px'); // NaN (關鍵差異)
Number(''); // 0
Number(' '); // 0
Number(null); // 0
Number(undefined); // NaN
Number(true); // 1
Number(false); // 0
+'42'; // 42
+'3.14'; // 3.14
+'42px'; // NaN
+''; // 0
+null; // 0
+undefined; // NaN
// 利用 ToInt32 抽象操作:轉 32 位有號整數
'42' | 0; // 42
'3.14' | 0; // 3 (截斷小數)
'42px' | 0; // 0 (非數字字串→0)
'' | 0; // 0
null | 0; // 0
undefined | 0; // 0
// 注意:超出 32 位範圍會溢位
'2147483648' | 0; // -2147483648 (溢位)
'-2147483649' | 0; // 2147483647 (溢位)
Math.trunc('42'); // 42
Math.trunc('3.14'); // 3
Math.trunc('42px'); // NaN
Math.trunc(''); // NaN
Math.trunc(null); // 0
Math.trunc(undefined); // NaN
/**
* 安全字串轉整數
* @param {any} value - 待轉換值
* @param {number} [defaultValue=0] - 轉換失敗預設值
* @param {Object} [options] - 選項
* @param {boolean} [options.allowFloat=false] - 是否允許浮點數 (用 parseFloat)
* @param {boolean} [options.clamp32=false] - 是否限制 32 位整數範圍
* @returns {number}
*/
function toInt(value, defaultValue = 0, options = {}) {
const { allowFloat = false, clamp32 = false } = options;
// 空值處理
if (value == null || value === '') return defaultValue;
// 已是數值
if (typeof value === 'number') {
if (!isFinite(value)) return defaultValue;
return clamp32 ? (value | 0) : (allowFloat ? value : Math.trunc(value));
}
// 字串處理
if (typeof value === 'string') {
const trimmed = value.trim();
if (!trimmed) return defaultValue;
const num = allowFloat ? parseFloat(trimmed) : parseInt(trimmed, 10);
if (isNaN(num)) return defaultValue;
return clamp32 ? (num | 0) : (allowFloat ? num : Math.trunc(num));
}
// 其他類型嘗試 Number()
const num = Number(value);
return isNaN(num) ? defaultValue : (clamp32 ? (num | 0) : (allowFloat ? num : Math.trunc(num)));
}
// 使用範例
toInt('42'); // 42
toInt('3.14'); // 3
toInt('3.14', 0, {allowFloat: true}); // 3.14
toInt('42px'); // 0 (預設值)
toInt('42px', null); // null
toInt('', 100); // 100
toInt(null, 100); // 100
toInt(undefined, 100); // 100
toInt(NaN, 100); // 100
toInt(Infinity, 100); // 100
toInt('2147483648', 0, {clamp32: true}); // -2147483648 (溢位)
const iterations = 1_000_000;
const testValues = ['42', '3.14', ' 42 ', '42px', '', null, undefined];
console.time('parseInt');
for (let i = 0; i < iterations; i++) parseInt(testValues[i % 7], 10);
console.timeEnd('parseInt'); // ~12ms
console.time('Number');
for (let i = 0; i < iterations; i++) Number(testValues[i % 7]);
console.timeEnd('Number'); // ~8ms
console.time('Unary +');
for (let i = 0; i < iterations; i++) +testValues[i % 7];
console.timeEnd('Unary +'); // ~6ms (最快)
console.time('Math.trunc');
for (let i = 0; i < iterations; i++) Math.trunc(testValues[i % 7]);
console.timeEnd('Math.trunc'); // ~10ms
console.time('Bitwise |0');
for (let i = 0; i < iterations; i++) (testValues[i % 7] | 0);
console.timeEnd('Bitwise |0'); // ~5ms (最快,但語意不同)
場景選擇:
├── 表單輸入驗證、API 參數處理 → toInt() 安全封裝函式
├── 確定是純數字字串、追求極致效能 → +str 或 str | 0
├── 需要保留小數 → parseFloat() 或 Number()
├── 嚴格模式:非純數字即失敗 → Number() 或 Math.trunc()
├── 位元運算/像素計算/哈希 → value | 0
├── 現代專案、需語意清晰 → Math.trunc() / Number()
└── 陣列索引運算 → ~~val 或 val | 0 (確保整數)
type NumericString = string & { __numericString: never };
function parseInteger(value: string | number | null | undefined, fallback = 0): number {
if (value == null) return fallback;
const num = typeof value === 'string' ? parseInt(value, 10) : Number(value);
return Number.isNaN(num) ? fallback : num;
}
// 使用
const userId = parseInteger(params.id, 0);
const page = parseInteger(searchParams.get('page'), 1);