加法賦值 (+=)

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

加法賦值 (+=) 運算子對兩個運算元執行加法(可以是數字加法或字串連線),並將結果賦給左運算元。

試一試

let a = 2;
let b = "hello";

console.log((a += 3)); // Addition
// Expected output: 5

console.log((b += " world")); // Concatenation
// Expected output: "hello world"

語法

js
x += y

描述

x += y 等同於 x = x + y,不同之處在於表示式 x 只會被求值一次。

示例

使用數字的加法賦值

js
let bar = 5;
bar += 2; // 7

其他非字串、非 BigInt 值將被強制轉換為數字

js
let baz = true;
baz += 1; // 2
baz += false; // 2

使用 BigInt 的加法賦值

js
let x = 1n;
x += 2n; // 3n

x += 1; // TypeError: Cannot mix BigInt and other types, use explicit conversions

使用字串的加法賦值

js
let foo = "foo";
foo += false; // "foofalse"
foo += "bar"; // "foofalsebar"

let bar = 5;
bar += "foo"; // "5foo"

規範

規範
ECMAScript® 2026 語言規範
# sec-assignment-operators

瀏覽器相容性

另見