(共566篇)
全部分类

JS的逻辑运算符&&和||中发生了什么
[ JS基础 ] 

项目中经常会用到这种写法

1
2
3
function add(x){
  const v  = x || 10
}

这个函数中的const v = x || 10意思很明显:

倘若x没有接受到参数,就把 10 赋值给常亮 v

还有这种写法(react中会很常用)

1
2
3
function build(){}
const allowRender = true;
allowRender && build()

这里allowRender && build()的意思都明白:如果allowRender为true,才会执行build函数

等等,教材上不是说&&|| 属于逻辑运算符吗?逻辑运算符的结果不应该是一个布尔值吗?那第一个案例中的v值难道不应该是true吗?

我认为各种教材上说的都不够严谨,严格来说,逻辑运算符的出现,是为了定义语句的执行顺序和执行条件.

&&表示只有该运算符前面的值为true或者前面表达式的结果为true或者被隐式转换为true时, 才会执行运算符后面的语句

看个🌰:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
true && (console.log(2)) 
// console会执行

false && (console.log(2)) 
// console不会执行

(a = 1) && (console.log(2)) 
// console会执行,因为赋值表达式的返回值是等号右边的值,这里是1,1会被隐式转换为true

(a = undefined) && (console.log(2)) 
// console不会执行,因为赋值表达式中等号右边是undefined,会被隐式转换为false

||表示只有该运算符前面的值为false或者前面表达式的结果为false或者被隐式转换为false时, 才会执行运算符后面的语句.

看看🌰:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
true || (console.log(2)) 
// console不会执行

false || (console.log(2)) 
// console会执行

(a = 1) || (console.log(2)) 
// console不会执行,因为赋值表达式的返回值是等号右边的值,这里是1,1会被隐式转换为true

(a = undefined) || (console.log(2)) 
// console会执行,因为赋值表达式中等号右边是undefined,会被隐式转换为false

那么在if语句中,为什么逻辑运算符的结果是布尔值呢?

1
2
3
4
const a ,b = 1;
if(a && b){
	console.log(1)
}

其实if语句中,如果括号内是不是直接的true或者fasle, 而是一个表达式, if会把表达式的结果隐式转换为true或者false, 再根据结果去判断是否执行大括号内的语句