在使用解构时,请确保将默认值设置为{},以防止它抛出错误,从而导致程序崩溃!

// ❌
function hi(person) {
  const { age } = person
}

hi() // TypeError

// ✅
function hi(person = {}) {
  const { age } = person
}

hi() 

为什么它抛出错误?

这是因为不能对值 undefinednull 进行解构。

const { age } = null
age // TypeError

const { name } = undefined
name // TypeError

当你调用一个函数而忘记传递一个参数时。默认情况下,该值为 undefined

function hi(person) {
  return typeof person
}

hi() // undefined

不会引发错误的其他值

下面是一个列表,您可以对其进行分解,以避免抛出错误。

const { emptyString } = ''
const { nan } = NaN
const { emptyObject } = {}

emptyString // undefined
nan // undefined
emptyObject // undefined