通过前缀和后缀运算符增加数字 [英] Increment a number by prefix and postfix operator

查看:117
本文介绍了通过前缀和后缀运算符增加数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

错误地,我写道:

++number++;

得到了这个:

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

为什么?除了这个之外,首先将数字增加1,然后再将数字再增加一个。

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

推荐答案

在JavaScript中, ++ 都是前缀 postfix 增量运算符。 postfix 运算符具有更高的优先级,因此当我们应用优先级时,您的表达式变为:

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++);

number ++ 的结果是一个值,不是变量引用,因此它不能是前缀增量运算符的操作数,原因相同 ++ 42 无效 —没有地方可以将结果写回。

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.

为什么它称之为左手边表达到运营商的?您必须查看V8源代码(我可以从V8上的错误文本中看出,可能是Chrome)。我可以推测这是因为许多运算符接受两个操作数(左和右),并且它们只调用一元运算符,如 ++ 默认情况下为左手。但这是猜测。

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.

这篇关于通过前缀和后缀运算符增加数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆