【问题标题】:TypeError: Cannot match against 'undefined' or 'null'TypeError:无法匹配“未定义”或“空”
【发布时间】:2016-09-24 00:11:46
【问题描述】:

代码

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)。

【问题讨论】:

    标签: javascript node.js ecmascript-6


    【解决方案1】:

    只有当被解构的数组或对象或其子对象是undefinednull 时才会出现此错误。

    没错。在您的情况下,被解构的对象是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'.
    

    【讨论】:

    • 你说得对,我被错误信息中的箭头误导了
    • @PrashanthChandra 如果仔细观察,箭头实际上指向左括号,而不是错误:-)
    • 很遗憾,最近刚刚发布的功能没有提供更多信息和有用的信息
    • 该死,我以为我发现了一个通过解构 undefined 来进行空值检查的优雅解决方案。哦,好吧,解构{} 对于处理具有默认函数值的空值仍然非常方便。
    • 这是有道理的。 :D
    猜你喜欢
    • 2019-03-07
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2018-09-30
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多