javascript - 类型错误 : Cannot match against 'undefined' or 'null'

标签 javascript node.js ecmascript-6

代码

client.createPet(pet, (err, {name, breed, age}) => {
  if (err) {
    return t.error(err, 'no error')
  }
  t.equal(pet, {name, breed, age}, 'should be equivalent')
})

错误

client.createPet(pet, (err, {name, breed, age}) => {
                        ^

TypeError: Cannot match against 'undefined' or 'null'.

为什么会出现此错误?我对 ES6 的了解使我假设只有当 数组或被解构的对象或其子对象undefinednull 时才会出现此错误。

我不知道函数参数被用作匹配项。如果它们是,那么为什么如果我尝试解构其中一个只是一个错误? (这不是 undefinednull)。

最佳答案

this error should only arise if the array or object being destructured or its children is undefined or null.

没错。在您的情况下,被解构的对象是 undefinednull。例如,

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'.

关于javascript - 类型错误 : Cannot match against 'undefined' or 'null' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37453235/

相关文章:

javascript - 传播运算符将对象转换为数组

javascript - 为什么 gulp 提示超出最大调用堆栈大小?

javascript - 如何禁止向 <td> 添加元素

javascript - 使用 javascript 和 python 在单节点中进行 Riak MapReduce

jquery - Angular $http.delete CORS 错误(预检请求)

javascript - 使用对象数组中的键查找 lastIndexOf() 对象

javascript - 如何链接包含 then 和 catch block 的嵌套 promise ?

javascript - 履行 promise

javascript - 根据 React.Js 中第一个下拉列表中的选择填充第二个下拉列表

javascript - MEANIO 4 个集群只为计划的作业运行一次?