运算符优先级

首先是从一道 面试题 引发的思考

1
2
3
4
5
6
var a = {n: 1}
var b = a;
a.x = a = {n: 2}

console.log(a.x); // undefined
console.log(b.x); // {n: 2}

各种解释 MDN 知乎

试着去读如下代码

a>b?a--:--a+b>b+c?a==b<c||a==c:(a+b)*a

c=3

执行前a 执行前b 执行结果 执行后a 执行后b
2 6 7 1 6
6 2 6 5 2
0 6 -5 -1 6

优先级大小依次降低:()、–、*、+、<、==、||、? :

运算符AST分析 分析地址1 分析地址2

分析这段代码a || b && c || d

Created with Raphaël 2.1.0ProgramExpressionStatementLogicalExpressionoperator: ||LogicalExpressionoperator: ||Identifiername: aLogicalExpressionoperator: &&Identifiername: bIdentifiername: cIdentifiername: d

|| 与 && 的短路求值语义,如果左操作数已经足以求出结果则不会对右操作数求值。

常用操作符优先级

逗号、赋值、条件、逻辑或、逻辑与、相等、比较、算术、前置递减、后置递减、成员访问、小括号