加法 (+)
加法運算子 (+) 對數字運算元進行求和,或對字串進行連線。
試一試
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"作為提示呼叫它,而模板字面量則使用"string"。這對於具有不同字串和原始值表示形式的物件來說很重要——例如Temporal,其物件的valueOf()方法都會丟擲錯誤。
js
const t = Temporal.Now.instant();
"" + t; // Throws TypeError
`${t}`; // '2022-07-31T04:48:56.113918308Z'
"".concat(t); // '2022-07-31T04:48:56.113918308Z'
建議不要使用 "" + x 來執行字串強制轉換。
示例
使用數字進行加法
js
1 + 2; // 3
其他非字串、非 BigInt 的值會被強制轉換為數字。
js
true + 1; // 2
false + false; // 0
使用 BigInt 進行加法
js
1n + 2n; // 3n
你不能在加法中混合使用 BigInt 和數字運算元。
js
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 進行加法運算,請轉換其中一個運算元。
js
1n + BigInt(2); // 3n
Number(1n) + 2; // 3
使用字串進行加法
如果其中一個運算元是字串,則另一個運算元會被轉換為字串並連線起來。
js
"foo" + "bar"; // "foobar"
5 + "foo"; // "5foo"
"foo" + false; // "foofalse"
"2" + 2; // "22"
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-addition-operator-plus |
瀏覽器相容性
載入中…