Number.parseInt()

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 2015 年 9 月以來,該特性已在各大瀏覽器中可用。

Number.parseInt() 靜態方法解析一個字串引數,並返回一個指定基數的整數。

試一試

function roughScale(x, base) {
  const parsed = Number.parseInt(x, base);
  if (Number.isNaN(parsed)) {
    return 0;
  }
  return parsed * 100;
}

console.log(roughScale(" 0xF", 16));
// Expected output: 1500

console.log(roughScale("321", 2));
// Expected output: 0

語法

js
Number.parseInt(string)
Number.parseInt(string, radix)

引數

string

要解析的值,強制轉換為字串。此引數開頭的空格將被忽略。

radix 可選

一個介於 236 之間的整數,表示 string基數(數學記數法中的基數)。

如果 radix 未定義或為 0,則假定其值為 10,除非數字以程式碼單元對 0x0X 開頭,在這種情況下,假定基數為 16

返回值

從給定的 string 解析出的整數。

如果 radix 小於 2 或大於 36,或者第一個非空格字元無法轉換為數字,則返回 NaN

示例

Number.parseInt 與 parseInt

此方法的功能與全域性 parseInt() 函式相同。

js
Number.parseInt === parseInt; // true

其目的是對全域性函式進行模組化。有關更多詳細資訊和示例,請參閱 parseInt()

規範

規範
ECMAScript® 2026 語言規範
# sec-number.parseint

瀏覽器相容性

另見