gpt4 book ai didi

javascript - 复杂的javascript条件表达式

转载 作者:数据小太阳 更新时间:2023-10-29 03:54:33 25 4
gpt4 key购买 nike

解释这个复杂的 javascript 表达式的正确方法是什么?

一些_条件? a = b : c = d = e;

遵循运算符优先级规则,我希望它是:

(some_condition ? a = b : c) = d = e;

但是看起来分组实际上是:

编辑:(原来的分组不清楚。更新见下文)

编辑:some_condition ? a = b : (c = d = e);

为什么会这样? (不,我没有写那个代码)

编辑:这似乎表明在 Javascript 中说 ?: 的优先级高于 = 并不完全正确。再举个例子:

x = y ? a = b : c = d = e;

如果 ?: 的优先级高于 =(如在 C 中),则分组将是

x = ((y ? a = b : c) = (d = e));

而是(从答案中)我们拥有的是

x = (y ? a = b : (c = d = e));

?:= 的相对优先级似乎取决于它们在表达式中的位置

最佳答案

如果您查看 javascript precedence operators , assignments 的优先级低于 conditional operator 但是,根据 ecmascript 规范,Par. 11.12

11.12 Conditional Operator ( ? : )     
Syntax

ConditionalExpression : LogicalORExpression
LogicalORExpression ? AssignmentExpression : AssignmentExpression

AssignmentExpression is evaluated as follows:
1. Let lref be the result of evaluating LogicalORExpression.
2. If ToBoolean(GetValue(lref)) is true, then
a. Let trueRef be the result of evaluating the first AssignmentExpression.
b. Return GetValue(trueRef).
...

因此,条件运算符会评估对每个赋值表达式进行分组的代码,并且它的工作原理与大家解释的一样。

也许我在这里可能是错的,但我认为运算符优先级与 js 如何解析像这样的表达式有关

a = (b < c)? b : c;

(而不是当包含在 AssignmentExpressions 中时)在这种情况下赋值应该具有较低的优先级,因此 Javascript 将整个语句评估为

a = ((b < c)? b : c);

关于javascript - 复杂的javascript条件表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9979429/

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