--- title: 運算子優先序 slug: Web/JavaScript/Reference/Operators/Operator_Precedence tags: - JavaScript - Operator - precedence translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence ---
運算子優先序(Operator precedence)決定了運算子彼此之間被語法解析的方式,優先序較高的運算子會成為優先序較低運算子的運算元(operands)。
當優先序相同時,使用相依性決定運算方向。範例如下:
a OP b OP c
左相依性 (Left-associativity) ,表示處理順序為從左至右 (a OP b) OP c,反之,右相依性(right-associativity) 表示處理順序為從右至左 a OP (b OP c)。賦值運算符 (Assignment operators) 為右相依性,範例如下:
a = b = 5;
a 和 b 的預期結果為 5,因為賦值運算符 (Assignment operator) 為右相依性,因此從右至左返回值。一開始 b 被設定為 5,接著 a 也被設定為 5。
下方表格列出運算子的相依性,從高 (20) 到低 (1)。
| 優先性 Precedence |
運算子名稱 Operator type |
相依性 Associativity |
運算子 Individual operators |
|---|---|---|---|
| 20 | {{jsxref("Operators/Grouping", "Grouping")}} | 無 | ( … ) |
| 19 | {{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation")}} | 從左至右 | … . … |
| {{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation")}} | 從左至右 | … [ … ] |
|
| {{jsxref("Operators/new","new")}} (with argument list) | 無 | new … ( … ) |
|
| Function Call | 從左至右 | … ( … ) |
|
| 18 | {{jsxref("Operators/new","new")}} (without argument list) | 從右至左 | new … |
| 17 | {{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment")}} | 無 | … ++ |
| {{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement")}} | … -- |
||
| 16 | Logical NOT | 從右至左 | ! … |
| Bitwise NOT | ~ … |
||
| Unary Plus | + … |
||
| Unary Negation | - … |
||
| Prefix Increment | ++ … |
||
| Prefix Decrement | -- … |
||
| typeof | typeof … |
||
| void | void … |
||
| delete | delete … |
||
| await | await … |
||
| 15 | Exponentiation | 從右至左 | … ** … |
| 14 | Multiplication | 從左至右 | … * … |
| Division | … / … |
||
| Remainder | … % … |
||
| 13 | Addition | 從左至右 | … + … |
| Subtraction | … - … |
||
| 12 | Bitwise Left Shift | 從左至右 | … << … |
| Bitwise Right Shift | … >> … |
||
| Bitwise Unsigned Right Shift | … >>> … |
||
| 11 | Less Than | 從左至右 | … < … |
| Less Than Or Equal | … <= … |
||
| Greater Than | … > … |
||
| Greater Than Or Equal | … >= … |
||
| in | … in … |
||
| instanceof | … instanceof … |
||
| 10 | Equality | 從左至右 | … == … |
| Inequality | … != … |
||
| Strict Equality | … === … |
||
| Strict Inequality | … !== … |
||
| 9 | Bitwise AND | 從左至右 | … & … |
| 8 | Bitwise XOR | 從左至右 | … ^ … |
| 7 | Bitwise OR | 從左至右 | … | … |
| 6 | Logical AND | 從左至右 | … && … |
| 5 | Logical OR | 從左至右 | … || … |
| 4 | Conditional | 從右至左 | … ? … : … |
| 3 | Assignment | 從右至左 | … = … |
… += … |
|||
… -= … |
|||
… **= … |
|||
… *= … |
|||
… /= … |
|||
… %= … |
|||
… <<= … |
|||
… >>= … |
|||
… >>>= … |
|||
… &= … |
|||
… ^= … |
|||
… |= … |
|||
| 2 | yield | 從右至左 | yield … |
| yield* | yield* … |
||
| 1 | Comma / Sequence | 從左至右 | … , … |