How is the ternary operator evaluated in JavaScript?

前端 未结 4 1044
猫巷女王i
猫巷女王i 2021-02-19 06:19

Regarding the ternary (? :) operator in JavaScript, I would like to know how it is evaluated by a typical browser\'s JavaScript interpreter:

Alternative A:<

4条回答
  •  旧时难觅i
    2021-02-19 06:23

    According to the specification it works like in Alternative A:

    The production ConditionalExpression : LogicalORExpression ? AssignmentExpression : AssignmentExpression is evaluated as follows:

    1. Let lref be the result of evaluating LogicalORExpression.
    2. If ToBoolean(GetValue(lref)) is true, then
      • Let trueRef be the result of evaluating the first AssignmentExpression.
      • Return GetValue(trueRef).
    3. Else
      • Let falseRef be the result of evaluating the second AssignmentExpression.
      • Return GetValue(falseRef).

提交回复
热议问题