admin管理员组

文章数量:1289483

I make an animation with this movement code:

x += -1

I'm just wondering what the difference is if i write this:

x -= 1

the result is still the same, but before i move any futher, is there are any difference in essence between the two?

Thanks.

I make an animation with this movement code:

x += -1

I'm just wondering what the difference is if i write this:

x -= 1

the result is still the same, but before i move any futher, is there are any difference in essence between the two?

Thanks.

Share Improve this question edited Apr 28, 2017 at 13:52 henrikmerlander 1,57413 silver badges20 bronze badges asked Mar 24, 2016 at 10:20 GarundangGarundang 191 silver badge2 bronze badges 2
  • 1 It is the same thing. it is like doing in math "a + -1" and "a-1" – AlainIb Commented Mar 24, 2016 at 10:23
  • 1 IMO I prefer read x -= if the logic is to sub on x – Hacketo Commented Mar 24, 2016 at 10:33
Add a ment  | 

3 Answers 3

Reset to default 9

x += -1 is shorthand for x = x + -1 while x -= 1 is shorthand for x = x - 1. This will produce the same result as long as x is a javascript Number. But because + can also be used for string concatenation, consider x being the String '5' for example and we will have this situation:

'5' + -1 = '5-1' and '5' - 1 = 4.

So it might be advisable to think twice before choosing which one instead of just blindly using them interchangeably.

What you have there are nothing more than shorthand operators. In the first case, it's an Addition Assignment, in the second case it's a Subtraction Assignment.

So your code x += -1 can be interpreted as follows:

x = x + -1; // which is the same as..
x = x - 1;  // which can be rewritten as..
x -= 1;

Mathematically there is no difference. 2 + -1 = 1 which is the same as 2 - 1 = 1

本文标签: Difference between1 and1 in JavascriptStack Overflow