Number.parseInt()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
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
小于 2
或大于 36
,或第一个非空白字符不能转换为数字,则返回 NaN
。
示例
Number.parseInt 与 parseInt 对比
这个方法和全局的 parseInt()
函数具有相同的功能:
js
Number.parseInt === parseInt; // true
其目的是对全局变量进行模块化,另见 parseInt()
获取更多详情和示例。
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-number.parseint |
浏览器兼容性
BCD tables only load in the browser