gpt4 book ai didi

javascript - 为什么 JavaScript UpdateExpression 语法如此定义?

转载 作者:行者123 更新时间:2023-11-29 15:14:18 26 4
gpt4 key购买 nike

根据 Ecma-262,前缀递增和递减运算符定义为:

UpdateExpression :
LeftHandSideExpression ++
LeftHandSideExpression ‐‐
++ UnaryExpression
‐‐ UnaryExpression

令人惊讶的是,后缀和前缀运算符都在同一规则中定义,而且它是 ++ UnaryExpression,而一般的一元表达式肯定不是更新的有效参数运营商。

UnaryExpression 本身中定义前缀递增和递减运算符以及其他前缀运算符似乎更清晰、更合乎逻辑,其他 C 语法语言也这样做,例如C 标准第 6.5.3 节定义 unary-expression 以包括前缀更新运算符和其他运算符。

为什么 JavaScript 会这样定义这些运算符?

最佳答案

Why does JavaScript define these operators the way it does?

它主要是历史性的,就像规范中的许多其他奇怪之处一样。

It would seem cleaner and more logical to define the prefix increment and decrement operators in UnaryExpression itself, along with the other prefix operators, and other C syntax languages do this

事实上,多年来,它就是这样定义的,在 ES5.1 中和 ES6 .它很简单,每个优先级别都有一个句法产生式(PostfixExpression 是下一个更严格的),并且可能在构思 JS 时直接继承自 C 或 Java 语法。

Surely a unary expression in general is not actually a valid argument for the update operators

在 C 中,-- -- x 实际上是有效的,所以这就是为什么前缀自增和自减运算符表达式包含另一个 UnaryExpression。当然,它会在尝试计算表达式时抛出异常,但在 ES5 中解析它可以正常工作。

ES6 然后添加了早期错误 的概念,现在增加和减少操作required a valid assignment target expression解析后。不过,这并没有编码在句法产生式中。

It is surprising that the postfix and prefix operators are defined in the same rule

这个定义是new in ES7 .它更改为 this commit引入了求幂运算符,其中PostfixExpression 被重命名为UpdateExpression 并且前缀运算符被移入规则。像这样的更改是必要的,因为 ** 运算符允许更新表达式,但不允许 UnaryExpression 作为其第一个参数(因为一元减号,如 -x ** 3,被认为太模糊了)。

关于javascript - 为什么 JavaScript UpdateExpression 语法如此定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50879753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com