搞定 JS 运算符:详解 || && 和神秘的 ??

165 阅读1分钟

一个概念

在JavaScript逻辑运算中0、”“、null、false、undefined、NaN都会判为false,其他都为true。

|| 运算

当表达式前面的为false时,直接取后面的值,不管后面是什么,当表达式前面为true,直接取前面的

总结:为真不走后面的,为假直接取后面的

  let testData
  testData = false || 0
  console.log('前面为假值: ', testData)
  testData = 1 || 0
  console.log('前面为真值: ', testData)
  console.log('--------------------')

image.png

&& 运算

如果表达式前面为假值,只取前面的,不走后面。如果表达式前面为真值,那就取后面的

总结:为假不走后面,为真取后面的

  testData = null && true
  console.log('前面为假值: ', testData)
  testData = true && undefined
  console.log('前面为真值: ', testData)

image.png

?? 运算

只当前面为null或者undefined时取后面的,否则取前面的

  let obj = {
    age: '',
  }
  testData = obj?.name ?? false
  console.log('为undefined: ', testData)

  testData = obj.age ?? false
  console.log('不为undefined: : ', testData)

image.png