簡體   English   中英

復雜的javascript條件表達式

[英]complicated javascript conditional expression

解釋這個復雜的javascript表達式的正確方法是什么?

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

遵循運算符優先級規則,我希望它是:

(some_condition ? 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 優先級運算符 ,則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);

這是一個縮寫if else語句

長形式將是

if(some condition)
{
 a = b;
}
else 
{
 c = d = e;
}
if( some_condition ){
    a=b;
}else{
    d=e;
    c=d;
}

var result = true ? a=b : c=d=e;

如果是真,則a等於b,結果等於b

var result = false ? a=b : c=d=e;

如果是假d等於e,c也等於e,結果是e

您可能還會發現三元運算符的這個定義很有用。

通常這將用於根據條件分配某些東西,但這個似乎只是根據條件改變acd

我經常看到像val = isConditionTrue ? trueVal : falseVal;這樣的東西val = isConditionTrue ? trueVal : falseVal; val = isConditionTrue ? trueVal : falseVal; 然后val可以是trueValfalseVal基於isConditionTrue

條件運算符定義為:

ConditionalExpression :
    LogicalORExpression
    LogicalORExpression ? AssignmentExpression : AssignmentExpression

a = bAssignmentExpression ,因此c = d = e

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM