Javascript logical operators tips


逻辑判断符

var a = b || c || d || e

var a 的值是从左到右第一个为true或者有值的变量

var a = b && c && d && e

var a的值为从左到右第一个为false或者没有值的变量

问号

问号可以避免undefined.某属性报错的问题

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// Expected output: undefined

用问号替代逻辑符号

let arr = res && res.data && res.data.list
let arr = res?.data?.list

let arr = res && res.data || []
let arr = res?.res?.data ?? []

A u t h o r: Joe
P o l i c y: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source Joe !
Leave Your Comment Here
  TOC