关于 JavaScript 中的三元 (? :
) 运算符,我想知道典型浏览器的 JavaScript 解释器如何评估它:
备选方案 A:
- 计算第一个操作数。
- 如果第一个操作数的结果为真,则评估并返回第二个操作数。
- 否则,评估并返回第三个操作数。
备选方案 B:
- 计算所有三个操作数。
- 如果第一个操作数的结果为真,则返回第二个操作数的结果。
- 否则,返回第三个操作数的结果。
选项 C:
当然,如果备选方案 A 和备选方案 B 都不能准确描述三元运算符的工作原理,请向我解释它是如何工作的。
最佳答案
According to the specification它的工作方式与备选方案 A 相同:
The production
ConditionalExpression : LogicalORExpression ? AssignmentExpression : AssignmentExpression
is evaluated as follows:
- Let
lref
be the result of evaluatingLogicalORExpression
.- If
ToBoolean(GetValue(lref))
istrue
, then
- Let
trueRef
be the result of evaluating the firstAssignmentExpression
.- Return
GetValue(trueRef)
.- Else
- Let
falseRef
be the result of evaluating the secondAssignmentExpression
.- Return
GetValue(falseRef)
.
关于javascript - 三元运算符在 JavaScript 中是如何求值的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5097346/