0
How to use += and -=
So it's come to my attention that when I look at some code I see -= += and it makes sense how they used them but I try and I cant.. So when and how is the appropriate and best time to use them
3 Antworten
+ 1
you can think of it as an operator. The function operator+=(a,b) will add b to a and save the value in a; then, it just returns a. Here an example:
https://code.sololearn.com/c90im60eT7R9/?ref=app
+ 4
An example is better than everything else...
x +=2 means x=x+2
x -=2 means x=x-2
x /=2 means x=x/2
x *=2 means x=x*2
those are short forms for operations and you can use them everytime you need to perform an operation...
clearer now? :)
+ 3
a += 2;
is the shorthand of
a = a + 2;
a -= 2;
is the shorthand of
a = a - 2;
a *= 2;
is the shorthand of
a = a * 2;
a /= 2;
is the shorthand of
a = a / 2;
a %= 2;
is the shorthand of
a = a % 1;
a ^= 2;
is the shorthand of
a = a ^ 2;
a |= 2;
is the shorthand of
a = a | 2;
a **= 2;
is the shorthand of
a = a ** 2;
(** is an operator for exponentiation in ES6)