【问题标题】:Destructure nested object with defaults, including nodes使用默认值解构嵌套对象,包括节点
【发布时间】:2017-01-16 22:42:17
【问题描述】:

使用 ECMAScript 6,我可以这样写:

const {
  a = mandatory('a'),
  b: {
    c = mandatory('c'),
    d = mandatory('d')
  } = mandatory('b')
} = { a: 'a', b: { c: 'c', d: 'd' } }
console.log(a, b, c, d)

function mandatory (field) {
  throw new Error(`Not giving you a ReferenceError today, but you must set a non-falsy value to "${field}"!`)
}

mandatory 是一个使用“默认语法”的函数,并打算在属性设置为假值时抛出“已知”错误。

当我运行代码时,我得到一个ReferenceError: b is not defined。如果我删除 d: 'd' 它突然不会再抛出错误了。

... = { a: 'a', b: { c: 'c' } }

它会抛出 desired 错误:

Error: Not giving you a ReferenceError today, but you must set a non-falsy value "d"!
  1. 如何定义b
  2. 如果 a.b 设置为非虚假值,我如何调用 mandatory 并抛出我自己的错误?

【问题讨论】:

  • 如果我删除 d: 'd' - 从哪里删除?这不在您发布的代码中。
  • 您的代码在 Node 6.2.2 中对我来说可以正常工作。
  • 抱歉,已修复。我添加了d: 'd'。所以“ReferenceError”是不需要的,但“Error”是需要的。

标签: javascript node.js ecmascript-6


【解决方案1】:

找到了解决办法。实际上,如果 b 具有虚假值,那么调用 mandatory 函数对我来说是没有意义的。如果cd确实存在,b 将是非虚假的。

但是要定义b以便进一步处理,可以这样做:

const {
  a = mandatory('a'),
  b, // Added this line
  b: {
    c = mandatory('c'),
    d = mandatory('d')
  }
} = { a: 'a', b: { c: 'c', d: 'd'} }
console.log(a, b, c, d)

function mandatory (field) {
  throw new Error(`Not giving you a ReferenceError today, but you must set "${field}"!`)
}

这不再给出参考错误。

【讨论】:

    【解决方案2】:

    b 未定义,因为没有这样的变量。 b: 只是分配给解构对象文字的值的属性名称,它不声明变量 b。要获得一个,您需要使用两个解构步骤:

    const {
      a = mandatory('a'),
      b = mandatory('b'),
    } = { a: 'a', b: { c: 'c', d: 'd' } },
    // or write `; const` here           ^
    {
      c = mandatory('b.c'),
      d = mandatory('b.d')
    } = b;
    console.log(a, b, c, d);
    

    【讨论】:

    • ?他的代码在 Firefox 控制台中对我来说运行良好
    • @Pointy 啊,我错过了使用重复属性名称的答案。
    猜你喜欢
    • 2020-04-09
    • 2019-09-30
    • 2020-12-07
    • 2014-08-12
    • 2020-01-05
    • 1970-01-01
    • 2019-03-31
    • 2019-07-23
    • 2017-12-09
    相关资源
    最近更新 更多