Javascript increment while assigning

℡╲_俬逩灬. 提交于 2019-12-05 07:50:53

It is saved, so it is similar to the first example. Take for example this code:

var v = 0;
v = ++v + ++v + ++v;
// Returns 6

That is because this will translate to:

v = (0+1) + ((0+1)+1) + (((0+1)+1)+1);

Or, to be more accurate:

v = 0+1 +
v = 1+1 + //Previous value of v + 1
v = 2+1   //Previous value of v + 1

Why?

++v will first save the incremented value of v, then it will return this incremented value.
To simplify things, try this in your console:

x = 0;
++x;

If ++x would resolve to x + 1, the value of x would now still be 0, right?
Nope, your x will be 1. This means that ++x must have a assignment operator in there.

Just try writing both ++x and x++ out in full English sentences:
++x: increment x by one and return the value
x++: return the value of x, and increment it.

Your second line (x = ++x;) is equivalent to x = (x += 1), yes.
Just look at any loop you've ever written:

for (var i = 0;i<100;i++)//<-- no need for another assign here

So you could've written ++x; all the same, but since that expression is the entire statement, it makes no difference if you write x++; or ++x...

As you probably know xxsomeVar increments the variable by 1, assigns the resulting value to that variable and then returns it, someVar++ returns the current value of the variable, and then increments it by 1 (the new value is assigned to the variable, too, of course).

So ++x; is the equivalent of x = (x + 1);

From the Language specs:
++prefix increment operator
Postfix++ increment operator

Doing:

var x = 0;
console.log(++x); // will make print 1

Doing :

var x = 0;
console.log(x++); // will make print 0
console.log(x); // will print 1

After reading the ECMAScript Language Specification in answer to the question it appears that ++x is equivalent to x = ( x = x + 1 ).

Translation of the steps outlined by the specification is:

  1. The result of the operation will be assigned to x
  2. Throw error if certain conditions are true
  3. oldValue = x
  4. newValue = oldValue + 1
  5. assign newValue to x
  6. return newValue

For the post-increment operator the above will return the oldValue instead of the newValue.

var x = 0;
// x is assigned 1 during the post-increment operation but because
// the oldValue is returned it is immediately replaced by 0.
x = x++; 
console.log( x ) // prints 0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!