加法赋值操作符 (+=
) 将右操作数的值添加到变量,并将结果分配给该变量。两个操作数的类型确定加法赋值运算符的行为。加法或串联是可能的。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Syntax
Operator: x += y Meaning: x = x + y
Examples
Using addition assignment
// Assuming the following variables
// foo = 'foo'
// bar = 5
// baz = true
// Number + Number -> addition
bar += 2 // 7
// Boolean + Number -> addition
baz += 1 // 2
// Boolean + Boolean -> addition
baz += false // 1
// Number + String -> concatenation
bar += 'foo' // "5foo"
// String + Boolean -> concatenation
foo += false // "foofalse"
// String + String -> concatenation
foo += 'bar' // "foobar"
Specifications
Specification |
---|
ECMAScript (ECMA-262) Assignment operators |
Browser compatibility
BCD tables only load in the browser