javascript - 未捕获的类型错误 : Cannot destructure property `name` of 'undefined' or 'null'

标签 javascript ecmascript-6 object-destructuring

在传递空对象的情况下,对象解构会引发错误

function test ({name= 'empty'}={}) {
  console.log(name)
}
test(null);


Uncaught TypeError: Cannot destructure property name of 'undefined' or 'null'. at test (:1:15) at :1:1

最佳答案

docs :

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.



换句话说,如果null,则不会分配默认参数。通过:

function fn(arg = 'foo') {
  console.log(arg);
}
fn(null);


改为在函数的第一行进行解构:

function test (arg) {
  const { name = 'empty' } = arg || {};
  console.log(name)
}
test(null);

关于javascript - 未捕获的类型错误 : Cannot destructure property `name` of 'undefined' or 'null' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54744949/

相关文章:

javascript - 对象解构或可选链哪个是更好的代码?

javascript - 对象解构的正确方法

javascript - 如何丑化javascript类?

javascript - Javascript 中的异步启动器

javascript - 如何从对象数组中为每个不同的 'number' 获取最大值为 'type' 的对象?

javascript - 如何测试变量是Map类型还是Array类型?

javascript - jQuery 事件处理程序和未声明的事件对象

javascript - 表单验证和数组,如何收缩多个 if 和 else 语句?

javascript - 动态显示json对象