null 是如何在解构和抛出错误中返回的

How have null returned in destructure vs throwing error

我有一个像这样的 JavaScript 解构:

const {
  data: {currentVal}
} = {
  data: {
    currentVal: "one"
  }
}

(工作意味着 currentVal 是“一”)

如果未定义数据,我的代码会出现以下错误:

error: Uncaught TypeError: Cannot read property 'currentVal' of undefined

也就是说,如果我将代码更改为

const {
  dataxxx: {currentVal}
} = {
  dataa: {
    currentVal: "one"
  }
}

有没有“?”我可以使用类型语法,以便 currentVal 最终未定义而不是抛出错误?

可以使用里面的默认值destructuring

const { data: {currentVal} = {}} = {
  dataa: {
    currentVal: "one"
  }
}
console.log(currentVal);