在使用解构时,请确保将默认值设置为空 {}
,以防止它抛出错误,从而导致程序崩溃!
// ❌
function hi(person) {
const { age } = person
}
hi() // TypeError
// ✅
function hi(person = {}) {
const { age } = person
}
hi()
这是因为不能对值 undefined
和 null
进行解构。
const { age } = null // TypeError
const { name } = undefined // TypeError
当你调用一个函数而忘记传递一个参数时。默认情况下,该值为 undefined
。
function hi(person) {
return typeof person
}
hi() // undefined
下面是一个列表,您可以对其进行解构,以避免抛出错误。
const { emptyString } = ''
const { nan } = NaN
const { emptyObject } = {}
emptyString // undefined
nan // undefined
emptyObject // undefined