大网数据广告活动
Web 标准与前端开发

减法(-)

· 52CE 我爱测

JavaScript Demo: Expressions - Subtraction operator

减法(-)运算符将两个操作数相减,并产生两者之差。

JavaScript Demo: Expressions - Subtraction operator

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

语法

x - y

描述

减法运算符将两个操作数转换为数值,并根据两个操作数的类型执行数字减法或 BigInt 减法。如果类型不匹配,则抛出 TypeError。

示例

数值减法

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

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

非数值减法

// 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 减法

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

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

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

规范

浏览器兼容性

参见

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。