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

后端 未结 7 976
感情败类
感情败类 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:14

    The Javascript parser is greedy (it matches the longest valid operator each time), so it gets the ++ operator from a++b, making:

    (a++) b
    

    which is invalid. When you put in spaces a + + b, the parser interprets it like this:

    (a) + (+b)
    

    which is valid and works out to be three.

    See this Wikipedia article on Maximal munch for more details.

提交回复
热议问题