Javascript 类型错误:无法匹配“未定义”或“空”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37453235/
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
TypeError: Cannot match against 'undefined' or 'null'
提问by Prashanth Chandra
Code
代码
client.createPet(pet, (err, {name, breed, age}) => {
if (err) {
return t.error(err, 'no error')
}
t.equal(pet, {name, breed, age}, 'should be equivalent')
})
Error
错误
client.createPet(pet, (err, {name, breed, age}) => {
^
TypeError: Cannot match against 'undefined' or 'null'.
Why am I getting this error? My knowledge of ES6 led me to presume that this error should only arise if the array or object being destructured or its childrenis undefined
or null
.
为什么我收到这个错误?我ES6的知识使我推测,如果只应出现此错误数组或对象被解构或者其子女是undefined
或null
。
I wasn't aware that function parameters are used as a match. And if they are then why is it only an error if I try to destructure one of them? (that isn't undefined
or null
).
我不知道函数参数被用作匹配项。如果它们是,那么为什么我尝试解构其中一个只是一个错误?(这不是undefined
或null
)。
回答by thefourtheye
this error should only arise if the array or object being destructured or its children is
undefined
ornull
.
如果数组或对象的存在解构或其子是应该只出现此错误
undefined
或null
。
Exactly. In your case, the object being destructured is either undefined
or null
. For example,
确切地。在您的情况下,被解构的对象是undefined
或null
。例如,
function test(err, {a, b, c}) {
console.log(err, a, b, c);
}
test(1, {a: 2, b: 3, c: 4});
// 1 2 3 4
test(1, {});
// 1 undefined undefined undefined
test(1);
// TypeError: Cannot match against 'undefined' or 'null'.