Javascript variable incrementing in evaluation?
If I have
a = 0;
if(a++ < 1){
console.log(a);
}
I get the value 1 in the console. If a became 1 with the incrementation, then why did the expression evaluate true?
开发者_StackOverflow中文版If I do
a = 0;
if(++a < 1){
console.log(a);
}
Then I don't get anything in the console, meaning the expression evaluated to be false.
I have always used variable++
to increment variables in for loops and the like. I have seen the ++variable
, but I assumed it was another way to write the same thing. Can someone explain what happens and why? What's the difference between the two?
Does ++variable
increment the variable at the time of evaluation, while variable++
increments after?
I have seen the
++variable
, but I assumed it was another way to write the same thing.
No, they're not the same at all.
++variable
is pre-increment. It incrementsvariable
and evaluates to the new value.variable++
is post-increment. It incrementsvariable
and evaluates to the old value.
This is common to most C-style languages, including C itself, C++, PHP, Java and Javascript.
i.e.:
Does
++variable
increment the variable at the time of evaluation, whilevariable++
increments after?
Yes, exactly. :)
There's a very important difference here. a++
increments a after evaluation, where ++a
increments before evaluation. Conveniently the position of the ++
is either before or after as well, so that's how you can remember which is which.
In other words, this is what you're effectively doing:
a = 0;
if (a < 1)
{
a = a + 1;
console.log(a);
}
else
{
a = a + 1;
}
It is post incrementing, so for the comparison it is 0
, then in the block statement it is 1
.
a = 0;
// v-----0 < 1
if(a++ < 1){
// now a has been incremented to 1
console.log(a);
}
The pre incrementing version looks like:
a = 0;
// v-----1 < 1
if(++a < 1){
// evaluate to false, so this doesn't run
console.log(a);
}
++var
adds one, then does the comparison.
var++
does the comparison, then adds one.
The trick is to remember it by the ++
coming before the variable (increment happens before), or after the variable (increment happens after).
精彩评论