javascript中++和+ = 1之间的差异 [英] Difference between ++ and +=1 in javascript
问题描述
有人可以解释为什么以下函数会给出不同的结果。第一个似乎不起作用,但第二个确实有效。我很困惑,因为我认为+ = 1而且++做了同样的事情。
Could somebody explain why the following functions give different results. The first does not seem to work, but the second does. I'm puzzled because I thought +=1 and ++ did the same thing.
(我不打算实际使用这段代码,只是为了证明其差异)。
(I'm not intending to actually use this code, it's just to demonstrate the difference).
/*function 1*/
function incrementIfZero1(base,element) {
if (element == 0) {
return base++;
}
else
{
return base;
}
};
/*function 2*/
function incrementIfZero2(base,element) {
if (element == 0) {
return base+=1;
}
else
{
return base;
}
};
incrementIfZero1(1,0) /* -> 1*/
incrementIfZero2(1,0) /* -> 2*/
非常感谢任何帮助。
谢谢,
罗宾
感谢您的回复,现在有意义。我也尝试过以下语句,结果与函数1相同:
Thank you for your replies, it makes sense now. I had also tried the following statement, which resulted in the same thing as function 1:
return (base++)
我现在感到惊讶的是,这并没有给出与功能2相同的结果 - 我本来希望括号为'强制'在返回之前对其进行评估。知道为什么不是这种情况吗?
I'm now surprised that this doesn't give the same result as function 2 - I would have expected the brackets to 'force' it to be evaluated before returning. Any idea why this is not the case?
推荐答案
当你 return base ++
它在增加之前返回base的值。你想做 ++ base
以确保首先发生增量然后返回
when you return base++
it returns the value of base just before it gets incremented. You want to do ++base
to make sure the increment happens first then it gets returned
否则 ++
与相同+ = 1
为了回应你的编辑,我尝试在括号中包装随机语句,并且大多数数学运算符按预期响应,这种增量似乎是免除的,可能是因为预增量与后增量的语法是高度有意的并且语句本身 返回 特定值,无论您是否将其包装在括号中
[edit] in response to your edit, i tried wrapping random statements in parentheses and most mathematical operators respond as expected, this incrementation seems to be exempt, likely because the syntax of pre-incrementation vs post-incrementation is highly intentional and the statement itself returns a specific value regardless of whether or not you wrap it in parentheses
这篇关于javascript中++和+ = 1之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!