JavaScript 求幂一元运算符设计决策

标签 javascript operator-precedence exponentiation ecmascript-2016

所以我在研究新的求幂运算符时发现不能在基数之前直接放置一元运算符。

let result = -2 ** 2; // syntax error
let result = -(2 ** 2); // -4
let x = 3;
let result = --x ** 2; // 4

来自documentation on MDN :

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.

我知道这是设计错误。我不明白这个设计决定。谁真的会对 -x ** 2 为负感到惊讶?这不仅遵循其他主流编程语言,而且遵循数百年来普遍使用并教授给每个高中代数学生的数学符号。

在 Javascript 中 '1'+ 2'12''1'-2-1-1**2 会引发错误,因为它可能不明确?帮助我理解这个设计决策。

最佳答案

I don't understand this design decision.

https://esdiscuss.org/topic/exponentiation-operator-precedencehttps://esdiscuss.org/topic/power-operator-why-does-2-3-throwshttps://github.com/rwaldron/tc39-notes/blob/master/es7/2015-09/sept-23.md#exponentiation-operatorhttps://github.com/rwaldron/tc39-notes/blob/master/es7/2015-09/sept-24.md#exponentiation-operator 阅读更多相关信息。

Who's really going to be surprised that -x ** 2 is negative?

足够多的人很重要。上述资源的一些相关引用:

  • 使 ** 绑定(bind)得比一元运算符更紧密会破坏 x**-2。有时使它更紧,有时更松散会太困惑,并导致其他优先级反转的机会。” - Waldemar Horwat
  • 考虑到 ** 在其他语言中的历史与一元比二进制绑定(bind)更紧密的一般模式之间的冲突,此时的任何解决方案都会让很多人感到困惑。” - Mark S. Miller
  • 承认重要空白的前景:-x**2 === -(x ** 2)-x ** 2 === (-x) ** 2 ”- Alexander Jones
  • "问题是,无论求幂表达式前的一元减号多么罕见,缺少字体较小的上标表明 -** 绑定(bind)得更紧密。事实上,除了点(一种特殊形式,其正确的操作数必须是词法标识符名称)和方括号(这本身不是中缀运算符),一元运算符在 JS 中比在 C 和其他 C 派生语言中的二元运算符绑定(bind)更紧密。” - Brendan Eich
  • 对于数学来说,-5<sup>2</sup> 似乎很明显。但是对于 -5 ** 2,因为中缀运算符周围有空格。即使没有空格,- 似乎也是文字的一部分。”- Dave Herman
  • [关于编程语言优先级],“实际上零个人从其他语言中获得了关于此的直觉。同意人们有 ** 是求幂运算符的直觉。但人们通常会尽量避免黑暗的 Angular 落,因此他们永远不会开发负碱基的直觉。”- Dave Herman

In Javascript '1'+ 2 is '12' and '1'-2 is -1 but -1**2 raises an error because it could be ambiguous?

好吧,他们在今天的语言扩展设计上付出了相当多的努力:-)这是他们可以达成共识的最佳解决方案。

关于JavaScript 求幂一元运算符设计决策,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47068812/

相关文章:

javascript - iframe 内的 Phantomjs uploadFile

c++ - 2 的幂的模幂

c++ - 巨大数字的有效指数(我说的是 Googols)

javascript - getElementById(...) 为 null - 具有 2 个变量的函数

javascript - 使用 Javascript 截取单个页面应用程序的屏幕截图

c++ - 对同一对象的链接操作和求值顺序

PHP7 method_exists 未捕获错误 : Function name must be a string

java - Java 中的模幂问题

Javascript - 将变量添加到代码字符串中

haskell - 神秘的串行端口行为