javascript 未捕获的类型错误:无法解构“未定义”或“空”的属性“名称”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54744949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot destructure property `name` of 'undefined' or 'null'
提问by rahlrokks
Object destructuring throws error in case of null object is passed
在传递空对象的情况下,对象解构会引发错误
function test ({name= 'empty'}={}) {
console.log(name)
}
test(null);
Uncaught TypeError: Cannot destructure property
nameof 'undefined' or 'null'. at test (:1:15) at :1:1
未捕获的类型错误:无法解构
name“未定义”或“空”的属性。在测试 (:1:15) 在 :1:1
回答by CertainPerformance
See the docs:
查看文档:
Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.
如果未传递值或未定义,则默认函数参数允许使用默认值初始化命名参数。
In other words, the default parameter will notbe assigned if nullgets passed:
换句话说,如果传递了默认参数,则不会分配null:
function fn(arg = 'foo') {
console.log(arg);
}
fn(null);
Destructure in the first line of the function instead:
在函数的第一行进行解构:
function test (arg) {
const { name = 'empty' } = arg || {};
console.log(name)
}
test(null);

