js 或|| 运算符的常见使用方法

378 阅读1分钟

两侧都是布尔值

常规用法—— ||运算符两侧有一个为true,结果即为true

console.log( true || true );        //true
console.log( true || false );       //true
console.log( false || true );       //true
console.log( false || false );      //false

两侧有一侧为布尔值

刷题时遇到过这种情况。 需要意识到两个重要知识点:

1.逻辑或 || 是短路运算符,短路运算符就是从左到右的运算中前者满足要求,就不再执行后者了。对于||运算符,如果第一个表达式的布尔值是true,就不须看第二个表达式的布尔值了,直接返回true或布尔值为true的表达式。对于多个用||运算符连接起来的表达式也是同理,从左到右当有一个表达式的布尔值为true,不用再看右边的表达式,直接返回true或布尔值为true的表达式。

2.js在逻辑判断中,0, -0, null, undefined, '', NaN, false 会被判断为false。其他的都会被判定为true。

console.log( true || 'a' );         //true----左侧为true,直接返回true
console.log( 'a' || true );         //a------左侧为'a',被判断为true,返回'a'
console.log( false || 'a' );        //a------左侧为false,看右侧'a',被判断为true,返回'a'
console.log( 'a' || false );        //a------左侧为'a',被判断为true,返回'a'

两侧没有布尔值

console.log( undefined || 'a' );    //a------左侧undefined被判断为false,看右侧'a',被判断true
console.log( null || 'a' );         //a------同上

||运算符的使用场景

let a = { name: 'zb',age: '99' }
let b = a.sex || '男'
console.log(b);

在vue的v-for循环下,有些值没有定义在被使用时会报错,使用||运算符当被遍历的对象没有某种属性时添加默认值,不影响加下来的操作。