Number() 构造函数

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

¥The Number() constructor creates Number objects. When called as a function, it returns primitive values of type Number.

语法

¥Syntax

js
new Number(value)
Number(value)

注意:Number() 可以与 new 一起调用,也可以不与 new 一起调用,但效果不同。参见 返回值

¥Note: Number() can be called with or without new, but with different effects. See Return value.

参数

¥Parameters

value

正在创建的对象的数值。

返回值

¥Return value

Number() 作为函数调用时(不带 new),它返回 value 强制转换为数字原语。具体来说,BigInts 值会转换为数字而不是抛出。如果 value 不存在,则变为 0

¥When Number() is called as a function (without new), it returns value coerced to a number primitive. Specially, BigInts values are converted to numbers instead of throwing. If value is absent, it becomes 0.

Number() 作为构造函数调用时(带有 new),它使用上面的强制过程并返回封装 Number 对象,该对象不是基元。

¥When Number() is called as a constructor (with new), it uses the coercion process above and returns a wrapping Number object, which is not a primitive.

警告:你应该很少发现自己使用 Number 作为构造函数。

¥Warning: You should rarely find yourself using Number as a constructor.

示例

¥Examples

创建 Number 对象

¥Creating Number objects

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

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

¥Using Number() to convert a BigInt to a number

Number() 是 BigInt 可以转换为数字而不抛出异常的唯一情况,因为它非常明确。

¥Number() is the only case where a BigInt can be converted to a number without throwing, because it's very explicit.

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 太大而无法达到 安全代表,这可能会导致精度损失。

¥Note that this may result in loss of precision, if the BigInt is too large to be safely represented.

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

规范

Specification
ECMAScript Language Specification
# sec-number-constructor

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看