search

Home  >  Q&A  >  body text

javascript - In js, which one of a++ and ++a appears first in an operation?

As in the title:


var a = 1;
var b = a++ + ++a;

一开始以为b的运算过程是 b = 1 + 3;
今天听说++a的优先级要高,所以实际的运算过程是后面的++a先计算,
所以实际的过程是 b = 2 + 2;

求证一下
大家讲道理大家讲道理2828 days ago682

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-05-18 11:00:47

    Read the documentation first: operator precedence

    Obviously, post-increment has higher priority than pre-increment.
    That is to say, calculate firsta++然后才是++a.

    So why does this operation expression end up as 2 + 2? 2 + 2
    因为这俩运算都比+运算优先级高。
    然后,虽然a++先运算,但是a自增要等到整个算式运算结束,而++a则是马上就自增。
    a++++a运算之后,+运算之前,a的值就是2
    最后整个算式运算结束,a才会自增到3Because these two operations have higher priority than the + operation.

    Then, although a++ is calculated first, the increment of a has to wait until the entire calculation is completed, while ++a is incremented immediately. . 🎜After the a++ and ++a operations, but before the + operation, the value of a is 2< /code>. 🎜Finally, when the entire calculation is completed, a will increase to 3. You can print it out and take a look. 🎜

    reply
    0
  • Cancelreply