Increment a number by prefix and postfix operator

牧云@^-^@ 提交于 2019-11-30 09:32:32

问题


By mistake, I wrote:

++number++;

and got this:

Uncaught ReferenceError: Invalid left-hand side expression in prefix operation

Why? I would except this to to first increment number by one and then increment number by one again.


回答1:


In JavaScript, ++ is both the prefix and postfix increment operator. The postfix operator has higher precedence, and so when we apply precedence, your expression becomes:

++(number++);

The result of number++ is a value, not a variable reference, and so it cannot be the operand of the prefix increment operator, for the same reason ++42 is invalid — there's nowhere to write the result back to.


Why does it call it the "left-hand side expression" when it's to the right of the operator? You'd have to look at the V8 source code (I can tell from the text of the error you're doing this on V8, probably Chrome). I can speculate that it's because many operators accept two operands (left and right), and that they just call the only operand to unary operators like ++ the "left-hand" by default. But that's speculation.



来源:https://stackoverflow.com/questions/32795850/increment-a-number-by-prefix-and-postfix-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!