此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Number() 构造函数

基线 广泛可用

自 2015年7月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

Number() 构造函数创建 Number 对象。当作为函数调用时,它返回 Number 类型的原始值。

语法

js
new Number(value)
Number(value)

备注:调用 Number() 时可以使用或不使用 new,但是效果不同。详见返回值部分。

参数

value

所创建对象的数值。

返回值

Number 作为构造函数调用(使用 new)时,它创建一个 Number 对象,这个对象不是原始值。

Number 作为普通函数调用时,它将参数强制转换为数字原始值BigInt 被转换为数字。如果值不能转换,则返回 NaN

警告:你会发现你很少会使用 Number 作为构造函数。

示例

创建 Number 对象

js
const a = new Number("123"); // a === 123 为 false
const b = Number("123"); // b === 123 为 true
a instanceof Number; // 为 true
b instanceof Number; // 为 false
typeof a; // "object"
typeof b; // "number"

使用 Number() 将 BigInt 转换为数字

Number() 是唯一可以将 BigInt 转换为数字而不抛出错误的情况,因为这是完全显式的转换。

js
+1n; // TypeError: Cannot convert a BigInt value to a number
0 + 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
js
Number(1n); // 1

注意,如果 BigInt 非常大,以至于不能安全地表示它,这种转换可能会损失精度。

js
BigInt(Number(2n ** 54n + 1n)) === 2n ** 54n + 1n; // false

规范

规范
ECMAScript® 2027 Language Specification
# sec-number-constructor

浏览器兼容性

参见