SoFunction
Updated on 2025-02-28

The difference between adding first and then adding ++Difference analysis of a and a++

The difference between adding first and adding then adding ++a, a++

start

What will the following code output?

var a = 1
var b = 1
var c = 1
(a++)
(++b)
((c += 1))

think

Starting from learning javascript, it's rightAdd firstandAfter addingIt's vague, and today, let's learn it.

  • When using variables,++After the variable, the variable will be returned first and then done++deal with.
  • Add first, contrary to the previous logic (calculate first, then return).
  • c += 1It can be understood asc = c + 1
  • Reduce firstandReduce after, same as above
var a = 1
var b = 1
var c = 1
(a++) // 1
(++b) // 2
((c += 1)) // 2

Supplement: In JavaScript, what is the difference between ++ in front and ++ in back

one、
++可以与输出语句写existone起,++写exist变量前and写exist变量后不是one个意思
++ i and i ++ 区别exist于运算顺序and结合方向。
existJavaScriptThere are two types of self-add operations,All operators are ++,The function is to add operators themselves 1。
in:
++ VAR It is called pre-self-added,The variables that follow perform self-add operations,Its operation is,Perform the self-add operation first,Quote againVARvalue。
VAR ++ It is called post-self addition,The variables preceding it perform self-add operations,Its operation is,Quote firstVARvalue,Then perform self-add operations。
如果自加语句独立成为one个单独的语句,Then the addition of the front and back is exactly the same。
for example单独的one行
a ++; and ++ a; 是one样的。
1
For example,Commonforcycle:
    for(i = 0; i < 100; i ++)
    for(i = 0; i < 100; ++i)
1
2
Used here ++ i and i ++ It's exactly the same,No difference。
two、
当运算变量本身value会exist自加语句中,Perform other operations at the same time,two者就有区别了。
for example
    var i = 0;
    while( i ++ < 10);
1
2
i会先and10Compare size,Then perform self-add。This wayi=10hour,退出cycle,再执行one次自加,After exitivalue为11。
If written
    while(++ i < 10);
1
Is it self-added first,Then with10Compare。这样existi=9hour,Add it first,geti=10,然后Compare就会退出cycle了。In this case,After exitivalue为10。
再举one个例子。
    var a, i = 10;
    a = i ++; //Here i must first assign value and then add it yourself.  After the statement is executed, a=10, i=11;1
2
If written:
    var a, i = 10;
    a = ++i; //herei要Add it first,再赋value。After the statement is executeda=11, i = 11;

Here is the article about the difference between adding first and adding later in JavaScript ++a, a++. This is all about this article. For more related content on the difference between js ++a and a++, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!