简体   繁体   中英

JavaScript increment (++) operator on both sides of an argument?

I'm struggling to understand the behaviour of Javascript's increment operator, and more specifically, why certain cases fail.

Why does adding increment operator on both sides of an argument fail?

EXAMPLE:

let a = 1;
++a++;

This returns a horrible error stating that:

ReferenceError: Invalid left-hand side expression in prefix operation

What does this mean, and should I be worried?

The increment operators work on variables, not on expressions. You can't increment a numeric expression:

3++ // Uncaught ReferenceError: Invalid left-hand side expression in postfix operation

The reason for this is that it must increment the value, then save it back to the variable . If you gave it any old numeric expression, what would it assign the result to?

One of the two operators will work, but it returns the result of the operation, which is an expression, not a variable:

++(a++)

The first operator, a++ , will increment a , and return the result: 2 . The second operator is then trying to perform the increment on the value 2 , which is invalid syntax.

该代码可以重写为: ++(a++) ,它将转换为++(1) ,然后是++1 ,这不是有效的表达式。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM