javascript - 为什么求幂运算符的左操作数为负时会出现语法错误?

标签 javascript operator-precedence exponent ecmascript-2016

<分区>

当我在 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.

关于javascript - 为什么求幂运算符的左操作数为负时会出现语法错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52105654/

相关文章:

c++ - C++ 中条件运算符中逗号运算符的优先级是多少?

java - Java 中的指数(足够简单)

javascript - 嵌套对象中 $parent 的 knockout 问题

javascript - Jquery 未定义

C 数学运算顺序

R 指数产生 NaN

python - 指数位数

javascript - parse.com 无法从对象获取值

javascript - 仅当我放置警报框但仅在 chrome 中时,AngularJs+Bootstrap+Typeahead+Ajax 才起作用

c++ - 复杂的 if 条件