javascript 计数器++与计数器=计数器+1;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30420758/
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-28 12:08:56  来源:igfitidea点击:

counter ++ vs counter = counter+1;

javascriptincrementoperator-keyword

提问by user3562812

var counter = 0;
var increment = function(){
    return counter++;
    // return counter=counter+1;
}

console.log(increment());

Why does counter ++;returns 0 but counter = counter +1;returns 1?

为什么计数器++;返回 0 但计数器 = 计数器 +1;返回 1?

回答by Amit Joki

The post-fix increment operator returns the current valuefor evaluation and thenincrements it, so the value change is noticeable when it is referenced for the second time.

post-fix increment 运算符返回当前值进行评估,然后将其递增,因此第二次引用时值的变化很明显。

So when the returnstatement is executed, the value has not yetbeen incremented. You can cross-check by doing the following:

所以,当return执行语句时,值没有尚未被递增。您可以通过执行以下操作进行交叉检查:

console.log(counter++); // 0
console.log(counter); // 1
return counter; // obviously 1

Try the pre-fix operator which increments and thenreturns the incrementedvalue to be evaluated.

尝试使用前缀运算符递增,然后返回要评估的递增值。

return ++counter; // 1 

回答by Alex McMillan

This is called prefix (++x) vs postfix (x++)and the only difference is really the order of operations:

这称为前缀 ( ++x) 与后缀 ( x++),唯一的区别实际上是操作顺​​序:

counter;

evaluates to a value. (0)

评估为一个值。(0)

counter++;

evaluates to a value (0), performs a calculation (0 -> 1) and modifies a variable (counter-> 1).

计算为值 (0),执行计算 (0 -> 1) 并修改变量 ( counter-> 1)。

++counter;

performs a calculation (0 + 1), modifies a variable (counter-> 1) and evaluates to a value (1).

执行计算 (0 + 1),修改变量 ( counter-> 1) 并计算出值 (1)。

回答by Mehedi Hasan

var counter = 0;

无功计数器 = 0;

var increment = function(){
// now counter is 0 and after return it increment it's value to 1
// return 0 then 0+1=1;
    return counter++;
// calculate like math, counter = 0+1 then counter = 1, now return 1;
    // return counter=counter+1;
}

console.log(increment());

In first scenario,

在第一个场景中,

return counter++;

This statement is postfix, and evaluates like

这个语句是后缀,并且评估如下

return 0; and then 0+1=1

In second scenario,

在第二种情况下,

return counter=counter+1;

Calculate like math,

像数学一样计算,

return counter = 0+1 then,
return counter = 1, 
return 1;