首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Operator Precedence

运算符的优先级决定了表达式中运算执行的先后顺序,优先级高的运算符最先被执行。

下面是一个简单的例子:

代码语言:javascript
复制
3 + 4 * 5 // returns 23

乘法运算符 ("*")比起加法运算符("+")有着更高的优先级,所以它会被最先执行。

结合性

结合性决定了拥有相同优先级的运算符的执行顺序。考虑下面这个表达式:

代码语言:javascript
复制
a OP b OP c

左结合(从左到右计算)相当于把左边的子表达式加上小括号(a OP b) OP c,类似的,右关联(从右到左计算)相当于a OP (b OP c)。赋值运算符是右关联的,所以你可以这么写:

代码语言:javascript
复制
a = b = 5;

结果 a和 b 的值都会成为5。这是因为赋值运算符的返回结果就是赋值运算符右边的那个值,具体过程是:b被赋值为5,然后a也被赋值为 b=5 的返回值,也就是5。

汇总表

下面的表将所有运算符按照优先级的不同从高到低排列。

Precedence

Operator type

Associativity

Individual operators

20

Grouping

n/a

( … )

19

Member Access

left-to-right

… . …

Computed Member Access

left-to-right

… …

new (with argument list)

n/a

new … ( … )

Function Call

left-to-right

… ( … )

18

new (without argument list)

right-to-left

new …

17

Postfix Increment

n/a

… ++

Postfix Decrement

n/a

… --

16

Logical NOT

right-to-left

! …

Bitwise NOT

right-to-left

~ …

Unary Plus

right-to-left

Unary Negation

right-to-left

Prefix Increment

right-to-left

++ …

Prefix Decrement

right-to-left

-- …

typeof

right-to-left

typeof …

void

right-to-left

void …

delete

right-to-left

delete …

15

Exponentiation

right-to-left

… ** …

14

Multiplication

left-to-right

… * …

Division

left-to-right

… / …

Remainder

left-to-right

… % …

13

Addition

left-to-right

… + …

Subtraction

left-to-right

… - …

12

Bitwise Left Shift

left-to-right

… << …

Bitwise Right Shift

left-to-right

… >> …

Bitwise Unsigned Right Shift

left-to-right

… >>> …

11

Less Than

left-to-right

… < …

Less Than Or Equal

left-to-right

… <= …

Greater Than

left-to-right

… > …

Greater Than Or Equal

left-to-right

… >= …

in

left-to-right

… in …

instanceof

left-to-right

… instanceof …

10

Equality

left-to-right

… == …

Inequality

left-to-right

… != …

Strict Equality

left-to-right

… === …

Strict Inequality

left-to-right

… !== …

9

Bitwise AND

left-to-right

… & …

8

Bitwise XOR

left-to-right

… ^ …

7

Bitwise OR

left-to-right

… | …

6

Logical AND

left-to-right

… && …

5

Logical OR

left-to-right

… || …

4

Conditional

right-to-left

… ? … : …

3

Assignment

right-to-left

… = …

| … += … |

| … -= … |

| … **= … |

| … *= … |

| … /= … |

| … %= … |

| … <<= … |

| … >>= … |

| … >>>= … |

| … &= … |

| … ^= … |

| … |= … |

| 2 | yield | right-to-left | yield … |

| yield* | right-to-left | yield* … |

| 1 | Spread | n/a | ... … |

| 0 | Comma / Sequence | left-to-right | … , … |

扫码关注腾讯云开发者

领取腾讯云代金券