js increment and decrement

Self-increasing

  • Through self-increment, the variable can be +1 on its own basis

  • After a variable is incremented, the value of the original variable will be incremented immediately by 1

  • There are two types of auto-increment: (a++) and (++a)
    whether it is a++ or ++a, the value of the original variable will be automatically increased by 1
    var a=10;
    a++;
    console,log(a); The result is 11
    var a=10;
    ++a;
    console,log(a); The result is also 11

    The difference is that the values ​​of a++ and ++ are different. The value of
    a++ is equal to the value of the original variable (the value before self-increment)
    var a=10;
    console,log(a++); The result is 10
    a++;
    console,log(a); a++ The value of is 10, but at this time the value of a is self-incremented on the basis of 10. The value of
    ++a is equal to the value of the original variable (the new value after self-increment)

For example: var a=10;
result=a++ + ++a +a; the result is 34

Reason: The
first time a++ is 10, but after the a++ operation, the value of a becomes 11, and the second time ++a increases by 1 to 12 based on 11, and the value of a changes at this time It becomes 12, so the value of the last a is 12.

The final result: result=10+12+12=34

Decrement

  • Through self-increment, the variable can be based on itself -1
  • After a variable is incremented, the value of the original variable will be decremented by 1 immediately
  • There are two types of self-increment (a–) and (–a)
    whether it is a– or –a, it will automatically decrement the value of the original variable immediately. The
    difference is that the values ​​of a– and --a are different and the value of
    a– is equal to The value of the original variable (the value before decrement)
    -the value of a is equal to the value of the original variable (the new value after decrement)

The principle of decrement is the same as that of increment.

For example:
var d=10
result= d -----d -d;
console.log(result); The result is -6

Reason: the
first time the value of d– is 10, but when the d– operation is completed, the value of d becomes 9, and the second time –d is decremented by 1 and the value is 8, at this time d The value of is 8, and the value of the last d is also 8.

The final result:
result=10-8-8=-6

Guess you like

Origin blog.csdn.net/weixin_48769418/article/details/107737169
Recommended