i = i ++和i = i + 1之间的差异 [英] Difference between i = i++ and i = i + 1
问题描述
https://www.hackerrank.com/challenges/compare-the-triplets
var alice = bob = 0;
if(a0 > b0){
alice = alice + 1;
} else if (a0 < b0) {
bob = bob + 1;
} else if (a1 > b1) {
alice = alice + 1;
} else if (a1 < b1) {
bob = bob + 1;
} else if (a2 > b2) {
alice = alice + 1;
} else if (a2 < b2) {
bob = bob + 1;
}
console.log(alice, bob);
VS
var alice = bob = 0;
if(a0 > b0){
alice = alice++;
console.log(alice);
} else if (a0 < b0) {
bob = bob++;
} else if (a1 > b1) {
alice = alice++;
} else if (a1 < b1) {
bob = bob++;
} else if (a2 > b2) {
alice = alice++;
} else if (a2 < b2) {
bob = bob++;
}
console.log(alice, bob);
第一个正常工作但第二个没有。有人可以帮助我两者之间有什么区别吗?
first one worked properly but the second one didn't. Can someone help me what are the differences between the two?
推荐答案
那是因为第一次一个为变量分配一个新值,而第二个返回并递增它。
That is because the first one assigns a new value to the variable, while the second one returns and increments it.
这是一个简单的变量赋值,其中 a + 1
的值分配给 A
。执行此行后, a
将增加1。
This is a simple variable assignment, where the value of a + 1
is assigned to a
. After this line executes, a
will be incremented by one.
这是增量运算符。它不仅将变量递增1,还返回其值。
This is the increment operator. It not only increments the variable by 1, but also returns its value.
-
++ a
称为预增量。它将a + 1
的值分配给a
,然后返回a <的值/ code>。
-
a ++
称为后增量。它首先返回a
的值,然后将a + 1
分配给A
。
++a
is called pre-increment. It assigns the value ofa + 1
toa
, then returns the value ofa
.a++
is called post-increment. It first returns the value ofa
, then assignsa + 1
toa
.
这是您看到的错误的原因。这意味着在您的初始示例中,这是您的代码中发生的情况:
This is the cause for the error you're seeing. It means that in your initial example, this is what happens in your code:
alice = alice++; // assings the original value of alice to alice, then increments it
console.log(alice); // still the initial value
通过预先递增变量,您将得到:
By pre-incrementing the variable, you would get:
alice = ++alice; // assings alice+1 to alice
console.log(alice); // now contains the value of alice+1
这篇关于i = i ++和i = i + 1之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!