浮生逆旅

JS中的逻辑运算符

字数统计: 497阅读时长: 2 min
2019/11/15 Share

引言

今天在日常搬砖过程中,遇到了一个刚开始看起来匪夷所思的问题,在写if判断条件时,逻辑运算符没有按照我想象的那样去运行,下面进入正题


逻辑运算符优先级

我们先进行事故现场模拟还原

1
2
3
4
5
6
7
8
9
10
11
12
13
const arr = [{
index: 0
}, {
index: 1
}, {
index: 2
}];
const currentIndex = 0;
if (currentIndex === arr[0] && arr[0].index) {
...
return;
}
...

按照我的想法,currentIndex === arr[0] && arr[0].index这个条件应该成立,会进入到if中,执行完浅层业务代码然后退出当前函数,但是,现实给予了我痛击:他没有进入if,我 debug 时眼睁睁看着跳过了if,进入了更深层的业务代码,然后系统挂掉了

调试控制台计算表达式

1
2
3
4
5
6
> currentIndex
0
> arr[0] && arr[0].index
0
> currentIndex === arr[0] && arr[0].index
false

与实际运行时效果一致,typeof看一下

1
2
3
4
> typeof currentIndex
'number'
> typeof arr[0] && arr[0].index
0

what?

为什么typeof arr[0] && arr[0].index0,而不是 'number'?

逼不得已,只能看下运算符符优先级

优先级 运算符
1 [] . ()
2 ++ – -~!delete new typeof void
7 == != === !==
11 &&

原来===的优先级为 7,而&&的优先级是 11,在currentIndex === arr[0]时这个判断条件就已经不成立了,所以跳过了if

至于typeof arr[0] && arr[0].index为什么是 0 而不是'number',是因为typeof的优先级高于&&,当执行完typeof arr[0]时,得到的值是'object',字符串'object'转换为 boolean 类型为true,然后进行短路与运算,最终得到arr[0].index的值,也就是0

1
2
3
4
> typeof arr[0]
'object'
> 'object' && arr[0].index
0

问题找到了,解决方案是使用()将后半段给扩起来

1
2
> currentIndex === (arr[0] && arr[0].index)
true

好了,终于破案了,哈哈!

拜~


CATALOG
  1. 1. 引言
  2. 2. 逻辑运算符优先级