当我在 JavaScript 中使用指数运算符 (**
) 时,它通常按预期工作:
2 ** 2 // 4
2 ** -2 // 0.25
但是当左操作数为负数
-2 ** 2
我收到一个语法错误:
Uncaught SyntaxError: Unexpected token **
我可以通过在 -2
周围加上括号来轻松绕过它
(-2) ** 2 // 4
但我很好奇是什么导致了这个错误。其他运算符(+ - */%
等)没有这个问题。为什么 **
运算符会发生这种情况?
此行为是有意为之的,目的是防止您编写模棱两可的表达式。 From MDN :
In most languages like PHP and Python and others that have an
exponentiation operator (**), 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.
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.
-2 ** 2;
// 4 in Bash, -4 in other languages.
// This is invalid in JavaScript, as the operation is ambiguous.
-(2 ** 2);
// -4 in JavaScript and the author's intention is unambiguous.