语法
js
new Number(value)
Number(value)
参数
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> |