减法(-)

减法 (-) 运算符将两个操作数相减,产生它们的差。

¥The subtraction (-) operator subtracts the two operands, producing their difference.

Try it

语法

¥Syntax

js
x - y

描述

¥Description

- 运算符针对两种类型的操作数进行重载:编号和 BigInt。它首先 将两个操作数强制转换为数值 并测试它们的类型。如果两个操作数都变成 BigInt,则执行 BigInt 减法;否则,执行数字减法。如果一个操作数变为 BigInt 而另一个操作数变为数字,则抛出 TypeError

¥The - operator is overloaded for two types of operands: number and BigInt. It first coerces both operands to numeric values and tests the types of them. It performs BigInt subtraction if both operands become BigInts; otherwise, it performs number subtraction. A TypeError is thrown if one operand becomes a BigInt but the other becomes a number.

示例

¥Examples

数字减法

¥Subtraction with numbers

js
// Number - Number -> subtraction
5 - 3; // 2

// Number - Number -> subtraction
3 - 5; // -2

非数字减法

¥Subtraction with non-numbers

js
// String - Number -> subtraction
"foo" - 3; // NaN; "foo" is converted to the number NaN

// Number - String -> subtraction
5 - "3"; // 2; "3" is converted to the number 3

使用 BigInt 进行减法

¥Subtraction with BigInts

js
// BigInt - BigInt -> subtraction
2n - 1n; // 1n

不能在减法中混合使用 BigInt 和数字操作数。

¥You cannot mix BigInt and number operands in subtraction.

js
2n - 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions
2 - 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions

规范

Specification
ECMAScript Language Specification
# sec-subtraction-operator-minus

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看