【问题标题】:Why is there a syntax error when the left operand of the exponentiation operator is negative? [duplicate]为什么取幂运算符的左操作数为负时会出现语法错误? [复制]
【发布时间】:2019-02-05 21:47:23
【问题描述】:

当我在 JavaScript 中使用指数运算符 (**) 时,它通常按预期工作:

2 ** 2   // 4
2 ** -2  // 0.25

但是当左操作数为负数时

-2 ** 2

我收到语法错误:

Uncaught SyntaxError: Unexpected token **

我可以通过在-2 周围加上括号来轻松绕过它

(-2) ** 2 // 4

但我很好奇是什么导致了这个错误。其他运营商(+ - * / % 等)没有这个问题。为什么** 运算符会发生这种情况?

【问题讨论】:

    标签: javascript operator-precedence exponent ecmascript-2016


    【解决方案1】:

    有趣。我确实在 Mozilla 上找到了一些文档,其中说明了为什么这是不可能的。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation

    2 ** -3 是可能的。

    【讨论】:

      【解决方案2】:

      这种行为是有意的,是为了防止您编写模棱两可的表达式。 From MDN:

      在大多数语言中,例如 PHP 和 Python 以及其他具有 求幂运算符(**),求幂运算符定义 具有比一元运算符更高的优先级,例如一元 + 和 一元 -,但也有一些例外。例如,在 Bash 中,** 运算符被定义为具有比一元运算符低的优先级。 在 JavaScript 中,不可能编写模棱两可的幂运算 表达式,即您不能放置一元运算符 (+/-/~/!/delete/void/typeof) 紧接在基数之前。

      -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.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-09
        • 2020-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多