为什么求幂运算符的左操作数为负时会出现语法错误?
Why is there a syntax error when the left operand of the exponentiation operator is negative?
当我在 JavaScript 中使用指数运算符 (**
) 时,它通常按预期工作:
2 ** 2 // 4
2 ** -2 // 0.25
但是当左操作数为负数时
-2 ** 2
我收到一个语法错误:
Uncaught SyntaxError: Unexpected token **
我可以通过在 -2
周围加上括号来轻松绕过它
(-2) ** 2 // 4
但我很好奇是什么导致了这个错误。其他运营商(+ - * / %
等)没有这个问题。为什么 **
运算符会发生这种情况?
有意思。我确实在 Mozilla 上找到了一些文档,其中说明了为什么这是不可能的。
2 ** -3 是可能的。
此行为是有意为之的,目的是防止您编写模棱两可的表达式。 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.
当我在 JavaScript 中使用指数运算符 (**
) 时,它通常按预期工作:
2 ** 2 // 4
2 ** -2 // 0.25
但是当左操作数为负数时
-2 ** 2
我收到一个语法错误:
Uncaught SyntaxError: Unexpected token **
我可以通过在 -2
(-2) ** 2 // 4
但我很好奇是什么导致了这个错误。其他运营商(+ - * / %
等)没有这个问题。为什么 **
运算符会发生这种情况?
有意思。我确实在 Mozilla 上找到了一些文档,其中说明了为什么这是不可能的。
2 ** -3 是可能的。
此行为是有意为之的,目的是防止您编写模棱两可的表达式。 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.