减法 (-)

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

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

试一试

console.log(5 - 3);
// Expected output: 2

console.log(3.5 - 5);
// Expected output: -1.5

console.log(5 - "hello");
// Expected output: NaN

console.log(5 - true);
// Expected output: 4

语法

js
x - y

描述

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

示例

使用数字进行减法

js
5 - 3; // 2
3 - 5; // -2

其他非 BigInt 值被强制转换为数字

js
"foo" - 3; // NaN; "foo" is converted to the number NaN
5 - "3"; // 2; "3" is converted to the number 3

使用 BigInt 进行减法

js
2n - 1n; // 1n

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

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

要使用 BigInt 和非 BigInt 进行减法,请转换其中一个操作数。

js
2n - BigInt(1); // 1n
Number(2n) - 1; // 1

规范

规范
ECMAScript® 2026 语言规范
# sec-subtraction-operator-minus

浏览器兼容性

另见