javascript javascript中++和+=1的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17241877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:35:10  来源:igfitidea点击:

Difference between ++ and +=1 in javascript

javascriptincrement

提问by RobinL

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.

有人可以解释为什么以下函数会给出不同的结果。第一个似乎不起作用,但第二个起作用。我很困惑,因为我认为 +=1 和 ++ 做了同样的事情。

(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*/

Any help is very much appreciated.

很感谢任何形式的帮助。

Thanks,

谢谢,

Robin

罗宾

[Edit:]

[编辑:]

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:

谢谢你的回复,现在说得通了。我还尝试了以下语句,结果与函数 1 相同:

return (base++)

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?

我现在很惊讶这不会给出与函数 2 相同的结果 - 我原以为括号会“强制”在返回之前对其进行评估。知道为什么不是这样吗?

采纳答案by Stephan

when you return base++it returns the value of base just before it gets incremented. You want to do ++baseto make sure the increment happens first then it gets returned

当你return base++在它增加之前返回 base 的值时。你想++base确保增量首先发生然后它被返回

otherwise ++is the same as +=1

否则+++=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 returnsa specific value regardless of whether or not you wrap it in parentheses

[编辑] 为了响应您的编辑,我尝试将随机语句括在括号中,并且大多数数学运算符都按预期响应,这种增量似乎可以免除,可能是因为预增量与后增量的语法是高度有意的,并且语句本身无论您是否将其括在括号中,都将返回一个特定值

回答by sonoftunk

You are returning base++. This is the postfix increment, thus, the increment is handled after the return. For this specific case, return ++base;would be correct

你回来了base++。这是后缀增量,因此,在返回后处理增量。对于这种特定情况,return ++base;是正确的

回答by bfavaretto

return (base++)

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++)

我现在很惊讶这不会给出与函数 2 相同的结果 - 我原以为括号会“强制”在返回之前对其进行评估。知道为什么不是这样吗?

The increment operation isevaluated, regardless of the brackets. The catch here is that expressions in JavaScript always result in a value, which is then returned. For example, when you do var x = 2 + 2, 2 + 2is evaluated, then "returned" to the =operator, which then assigns that value to x. The ++postfix operator (as in base++) works differently: it does increment the variable preceding it, but the expression returns the value before incrementation. The prefix increment operator, on the other hand, works as you want, ++basereturns the value after incrementing it.

该增值业务评估,无论括号。这里的问题是 JavaScript 中的表达式总是产生一个值,然后返回该值。例如,当您执行var x = 2 + 2,2 + 2被评估,然后“返回”给=运算符,然后将该值分配给x。所述++后缀运算符(如base++)的工作方式不同:它确实增加其之前的变量,但递增之前表达式返回的值。另一方面,前缀增量运算符按您的需要工作,++base在增加它后返回值。

回答by Dan455

return base++;

Is post-increment. It increments the value held by base, and then returns the original value before the increment happened.

是后增量。它递增 base 持有的值,然后返回递增发生前的原始值。

return base += 1;

Adds one to base, and then returns base. This is a pre-increment. This can also be written as:

给基数加一,然后返回基数。这是一个预增量。这也可以写成:

return ++base;

回答by Dany Caissy

Just to clarify a little.

只是为了澄清一点。

"variable += 1" is the equivalent of "variable = variable + 1". It is NOT the equivalent of variable++!

“变量+= 1”相当于“变量=变量+ 1”。它不等同于变量++!

Something like variable++ can be used in-place, the former is an assignation.

像 variable++ 这样的东西可以就地使用,前者是赋值。

回答by Danny

Warning! There's a difference when two different types, a string and a number, are mutated using ++and +=:

警告!使用++and 对两种不同类型(字符串和数字)进行变异时会有所不同+=

When countis a string, count += 1seems to do type conversion and converts the 2nd number to a string, whereas count++takes the string countargument, converts to a number, and increments by 1.

count是字符串时,count += 1似乎进行类型转换并将第二个数字转换为字符串,而count++采用字符串count参数,转换为数字,并以 1 递增。

let count = process.argv[2]

while (count < 5) {
  console.log('Inside of the loop. Count is', count)
  count += 1 // NOT likely what you want! Now, try it with count++
}

console.log('Outside of loop. Count is', count)

Another example:

另一个例子:

> let num = '2'
undefined
> num++
2
> num
3

// VS using +=

> let num2 = '2'
undefined
> num2 += 1
'21'
> num2
'21'

回答by Danny

be carefull :

小心点 :

x = 1; y = (x++ * 10 + 1);

x = 1; y = (x++ * 10 + 1);

equal to :

等于 :

y = 1 * 10 + 1 = 11

y = 1 * 10 + 1 = 11

indeed :

的确 :

x = 1; y = (++x * 10 + 1);

x = 1; y = (++x * 10 + 1);

equal to :

等于 :

y = 2 * 10 + 1 = 21;

y = 2 * 10 + 1 = 21;

to finish :

完成 :

++x ;

++x;

or

或者

x++ ;

x++ ;

there are not difference !

没有区别!

回答by Usual Suspect

In The first function what happens is:

在第一个函数中发生的是:

return base++;// at first base value is returned and then incremented.

return base++;// 首先返回基值,然后递增。

In the 2nd Function :

在第二个功能中:

return base+=1;//here the incrementation is done first and then the variable is returned.

return base+=1;//这里首先完成增量,然后返回变量。

shorthand assignment has higher priority i.e. it finishes it's job in that line itself

速记分配具有更高的优先级,即它在该行本身完成它的工作