为什么-1 ** 2 javaScript中的语法错误?
在浏览器控制台中执行它,它说 SyntaxError:意外的令牌**
。
在节点中尝试它:
> -1**2
...
...
...
...^C
我认为这是算术表达式,其中 **
是电源运算符。其他运营商没有这样的问题。
奇怪的是,在第二行上键入*/
触发执行:
> -1**2
... */
-1**2
^^
SyntaxError: Unexpected token **
这里发生了什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为那是 spec 。设计这种方式是为了避免混淆它是一个(即
(-1)** 2
)的否定的平方,还是一个正方形的否定(IE- (1) ** 2)
)。该设计是广泛讨论对操作员优先级的广泛讨论,并检查如何处理此操作的方法。在其他语言中,最后决定通过将其作为语法错误来避免出乎意料的行为。Because that's the spec. Designed that way to avoid confusion about whether it's the square of the negation of one (i.e.
(-1) ** 2
), or the negation of the square of one (i.e.-(1 ** 2)
). This design was the result of extensive discussion of operator precedence, and examination of how this is handled in other languages, and finally the decision was made to avoid unexpected behavior by making this a syntax error.来自::
原因也在同一文本中解释:
因此,为避免混乱,决定代码必须删除歧义并明确放置括号:
或:
作为旁注, binary
-
未对此进行处理 - - 具有较低的优先级 - 因此,最后一个表达式具有与此有效表达式相同的结果:其他编程语言中的指示优先级
,如上所述,大多数具有Infix Exponention Operator的编程语言,对该操作员给予更高的优先级而不是一般的负。
以下是一些编程语言的其他示例,这些
From the documentation on MDN:
The reason is also explained in that same text:
So to avoid confusion it was decided that the code must remove the ambiguity and explicitly put the parentheses:
or:
As a side note, the binary
-
is not treated that way -- having lower precedence -- and so the last expression has the same result as this valid expression:Exponentiation Precedence in Other Programming Languages
As already affirmed in above quote, most programming languages that have an infix exponentiation operator, give a higher precedence to that operator than to the unary minus.
Here are some other examples of programming languages that give a higher precedence to the unary minus operator: