在传递空对象的情况下,对象解构会引发错误
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/