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
3 Answers
Reset to default 9x += -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
版权声明:本文标题:Difference between += -1 and -= 1 in Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741449984a2379431.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论