#### 4.11.1 Assignment with Operation

4.11.1 Assignment with Operation

Besides the normal = assignment operator, JavaScript supports a number of other assignment operators that provide shortcuts by combining assignment with some other operation. For example, the += operator performs addition and assignment. The following expression:

total += sales_tax

is equivalent to this one:

total = total + sales_tax

As you might expect, the += operator works for numbers or strings. For numeric operands, it performs addition and assignment; for string operands, it performs concatenation and assignment.

Similar operators include -=, *=, &=, and so on. Table 4-2 lists them all.

Table 4-2. Assignment operators

Operator Example Equivalent

+= a += b a = a + b -= a -= b a = a - b *= a *= b a = a * b /= a /= b a = a / b %= a %= b a = a % b <<= a <<= b a = a << b

Operator Example Equivalent

>>= a >>= b a = a >> b

>>>= a >>>= b a = a >>> b &= a &= b a = a & b |= a |= b a = a | b

^= a ^= b a = a ^ b

In most cases, the expression:

a op= b

where op is an operator, is equivalent to the expression: a = a op b

In the first line, the expression a is evaluated once. In the second it is evaluated twice. The two cases will differ only if a includes side effects such as a function call or an increment operator. The following two assignments, for example, are not the same:

欢迎转载,转载请注明来自一手册:http://yishouce.com/book/1/31329.html