Why does “a + + b” work, but “a++b” doesn't?

后端 未结 7 975
感情败类
感情败类 2020-12-24 05:35

I was fiddling around with different things, like this

var a = 1, b = 2;
alert(a + - + - + - + - + - + - + - + b); //alerts -1

and I could

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-24 06:23

    Javascript's operator precendence rules for the ++ increment operator has no left-right associativitity. That means a++b can be interpreted as a++ b or a ++b depending on the particular implementation. Either way, it's a syntax error, as you've got 2 variables, one unary-operator, and nothing joining the two variables.

    In practical terms:

    a = 1
    b = 2;
    
    a++ b; -> 2 2
    a ++b; -> 1 3
    

    What does 1 3 mean as JS code?

提交回复
热议问题