加法(+)

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

加法+)运算符计算数字操作数或字符串连接的总和。

尝试一下

console.log(2 + 2);
// Expected output: 4

console.log(2 + true);
// Expected output: 3

console.log("hello " + "everyone");
// Expected output: "hello everyone"

console.log(2001 + ": A Space Odyssey");
// Expected output: "2001: A Space Odyssey"

语法

js
x + y

描述

加法运算符(+)为两种不同的运算重载:数字加法和字符串连接。在求值时,它首先将两个操作数强制转换为基本类型。然后,检查两个操作数的类型:

  • 如果有一方是字符串,另一方则会被转换为字符串,并且它们连接起来。
  • 如果双方都是 BigInt,则执行 BigInt 加法。如果一方是 BigInt 而另一方不是,会抛出 TypeError
  • 否则,双方都会被转换为数字,执行数字加法。

字符串连接经常被认为等价于模板字符串或者 String.prototype.concat(),但并非如此。加法强制将表达式转为基本类型,它优先调用 valueOf();另一方面,模板字符串和 concat() 则强制将表达式转为字符串,它们优先调用 toString()。如果表达式有 [Symbol.toPrimitive]() 方法,字符串连接时会用 "default" 作为 hint 调用它,然而模板字符串则用 "string"。这对于具有不同的字符串和原始值表现的对象来说很重要——例如 Temporal,它的 valueOf() 方法会抛出错误。

js
const t = Temporal.Now.instant();
"" + t; // 抛出 TypeError
`${t}`; // '2022-07-31T04:48:56.113918308Z'
"".concat(t); // '2022-07-31T04:48:56.113918308Z'

建议不要使用 "" + x 来执行字符串强制转换

示例

数字加法

js
// Number + Number -> addition
1 + 2; // 3

// Boolean + Number -> addition
true + 1; // 2

// Boolean + Boolean -> addition
false + false; // 0

字符串连接

js
// String + String -> concatenation
"foo" + "bar"; // "foobar"

// Number + String -> concatenation
5 + "foo"; // "5foo"

// String + Boolean -> concatenation
"foo" + false; // "foofalse"

// String + Number -> concatenation
"2" + 2; // "22"

规范

Specification
ECMAScript® 2025 Language Specification
# sec-addition-operator-plus

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
Addition (+)

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见