为什么 -1**2 在 JavaScript 中是语法错误?
Why is -1**2 a syntax error in JavaScript?
在浏览器控制台中执行它显示 SyntaxError: Unexpected token **
。
在节点中尝试:
> -1**2
...
...
...
...^C
我认为这是一个算术表达式,其中 **
是幂运算符。其他运营商没有这个问题。
奇怪的是,在第二行输入 */
会触发执行:
> -1**2
... */
-1**2
^^
SyntaxError: Unexpected token **
这里发生了什么?
Executing it in the browser console says SyntaxError: Unexpected token **.
因为这是 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 运算符优先级,并检查了其他语言中的处理方式,最后决定通过将其设为语法错误来避免意外行为。
In JavaScript, it is impossible to write an ambiguous exponentiation expression, i.e. you cannot put a unary operator (+
/-
/~
/!
/delete
/void
/typeof
) immediately before the base number.
原因在同一篇文章中也有解释:
In most languages like PHP and Python and others that have an exponentiation operator (typically ^
or **
), the exponentiation operator is defined to have a higher precedence than unary operators such as unary +
and unary -
, but there are a few exceptions. For example, in Bash the **
operator is defined to have a lower precedence than unary operators.
因此,为了避免混淆,决定代码必须消除歧义并明确放置括号:
(-1)**2
或:
-(1**2)
作为旁注,binary -
没有那样处理——具有较低的优先级——所以最后一个表达式与这个表达式有相同的结果有效表达式:
0-1**2
其他编程语言中的求幂优先级
正如上面引文中已经确认的那样,大多数具有中缀求幂运算符的编程语言对该运算符的优先级高于一元减号。
这里有一些编程语言的其他例子,它们赋予一元减号运算符更高的优先级:
在浏览器控制台中执行它显示 SyntaxError: Unexpected token **
。
在节点中尝试:
> -1**2
...
...
...
...^C
我认为这是一个算术表达式,其中 **
是幂运算符。其他运营商没有这个问题。
奇怪的是,在第二行输入 */
会触发执行:
> -1**2
... */
-1**2
^^
SyntaxError: Unexpected token **
这里发生了什么?
Executing it in the browser console says SyntaxError: Unexpected token **.
因为这是 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 运算符优先级,并检查了其他语言中的处理方式,最后决定通过将其设为语法错误来避免意外行为。
In JavaScript, it is impossible to write an ambiguous exponentiation expression, i.e. you cannot put a unary operator (
+
/-
/~
/!
/delete
/void
/typeof
) immediately before the base number.
原因在同一篇文章中也有解释:
In most languages like PHP and Python and others that have an exponentiation operator (typically
^
or**
), the exponentiation operator is defined to have a higher precedence than unary operators such as unary+
and unary-
, but there are a few exceptions. For example, in Bash the**
operator is defined to have a lower precedence than unary operators.
因此,为了避免混淆,决定代码必须消除歧义并明确放置括号:
(-1)**2
或:
-(1**2)
作为旁注,binary -
没有那样处理——具有较低的优先级——所以最后一个表达式与这个表达式有相同的结果有效表达式:
0-1**2
其他编程语言中的求幂优先级
正如上面引文中已经确认的那样,大多数具有中缀求幂运算符的编程语言对该运算符的优先级高于一元减号。
这里有一些编程语言的其他例子,它们赋予一元减号运算符更高的优先级: