加法(+)
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);
// 預期輸出:4
console.log(2 + true);
// 預期輸出:3
console.log("哈囉 " + "大家");
// 預期輸出:「哈囉 大家」
console.log(2001 + ":太空漫遊");
// 預期輸出:「2001:太空漫遊」
語法
x + y
描述
+
運算子被重載用於兩種不同的操作:數值加法與字串串接。在運算時,它會先將兩個運算元強制轉換為原始型別。接著,會檢查這兩個運算元的型別:
- 如果其中一方是字串,另一個運算元也會轉換為字串,然後進行串接。
- 如果兩者都是 BigInt,則執行 BigInt 加法。如果一方是 BigInt 但另一方不是,則會拋出
TypeError
。 - 否則,兩邊都會轉換為數字,然後執行數值加法。
字串串接常被認為等同於模板字面值或 String.prototype.concat()
,但並非如此。加法會將運算式強制轉換為原始型別,此過程會優先呼叫 valueOf()
;而模板字面值與 concat()
則會將運算式強制轉換為字串,優先呼叫 toString()
。如果運算式有 [Symbol.toPrimitive]()
方法,字串串接時會以「default」作為提示呼叫,而模板字面值則使用「string」。這對於具有不同字串與原始值表示的物件很重要,例如 Temporal,其 valueOf()
方法會拋出例外。
const t = Temporal.Now.instant();
"" + t; // 拋出 TypeError
`${t}`; // '2022-07-31T04:48:56.113918308Z'
"".concat(t); // '2022-07-31T04:48:56.113918308Z'
建議你不要使用 "" + x
來進行字串強制轉換。
範例
使用數字加法
1 + 2; // 3
其他非字串、非 BigInt 的值會被轉換為數字:
true + 1; // 2
false + false; // 0
使用 BigInt 加法
1n + 2n; // 3n
你不能在加法中混用 BigInt 與數字運算元。
1n + 2; // TypeError: Cannot mix BigInt and other types, use explicit conversions
2 + 1n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
"1" + 2n; // TypeError: Cannot mix BigInt and other types, use explicit conversions
若要將 BigInt 與非 BigInt 進行加法,請強制轉換任一運算元:
1n + BigInt(2); // 3n
Number(1n) + 2; // 3
使用字串加法
如果其中一個運算元是字串,另一個會被轉換為字串並進行串接:
"foo" + "bar"; // 「foobar」
5 + "foo"; // 「5foo」
"foo" + false; // 「foofalse」
"2" + 2; // 「22」
規範
Specification |
---|
ECMAScript® 2026 Language Specification # sec-addition-operator-plus |