JS中?.、??、??=的用法和使用场景

120 阅读2分钟

前言

运算符中?.????=nullundefined这种空值有着更好的应对方式。之前每次如果要继续往下操作,都要先去判断值是否是nullundefined。有了这些摸鱼的时间的变多了。

可选链运算符(?.)

描述: 我们访问对象中某个属性或者调用函数时,当属性或调用的函数为nullundefined,则会报Uncaught TypeError: Cannot read properties of [null|undefined] (reading '(某个属性或者函数名)')

举个例子:

const obj = {
    name:'tom'
    a:{
        b:1
    }
}

console.log(obj.c.name) //  Uncaught TypeError: Cannot read properties of undefined (reading 'name') 因为obj对象里面没有c属性所以访问不到c属性里面的name属性。

// 使用 ?. 
console.log(obj.c?.name) // undefined  当使用?.可选链运算符时,相当于做了下面这一步判断操作
obj.c === undefined || obj.c === null ? undefined : obj.c.name

注意:

  • 可选链运算符不能用于未声明的根对象,但可以用于值为 undefined 的根对象。

    •   console.log(a?.b) // 因为a没有声明,所以这里不能使用可选链运算符
        
        const c = undefined
        console.log(c?.d) // 这样是可以的
      
  • 在数组中使用可选链运算符属性要配合方括号使用

    •   function printMagicIndex(arr) {
          console.log(arr?.[42]);
        }
        
        printMagicIndex([0, 1, 2, 3, 4, 5]); // undefined
        printMagicIndex(); // undefined;如果未使用 ?. 运算符,这将抛出一个错误:“Cannot read properties of undefined (reading '42')”
      
  • 可选链表达式的结果赋值是无效的

    •   const object = {};
        
        object?.property = 1; // SyntaxError: Invalid left-hand side in assignment
      

空值合并运算符(??)

描述:

当左侧的操作数为 null或者undefined时,返回其右侧操作数,否则返回左侧操作数。

举个例子:

const result = null ?? 'Hello World'

console.log(result) // 'Hello World'

// 这里也相当于做了下面这操作
result || 'Hello World'

注意:

  • ??与逻辑或运算符||相似,但||左边不仅仅是nullundefined返回右侧操作数,还包括任何假值(例如0、' '),还得注意??的优先级

    • 0 ?? 'Hello World'  // 0
      '' ?? 'Hello World' // ''
      null || undefined ?? 'Hello World' // 报错 
      (null || undefined) ?? 'Hello World' // 'Hello World'
      

逻辑空赋值(??=)

描述:

??运算符类似,多了一个赋值操作(相当于给个默认值)

举个例子:

const obj = {a:1}

obj.a ??= 10
obj.b ??= 2

console.log(obj.a) // 1
console.log(obj.b) // 2

注意:

  • 只有nullundefined才会使用??=右边的值,其他的都是用原本的值