Destructure使用默认值嵌套对象,包括节点

用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' } } 

它抛出了一个期望的错误:

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

find解决scheme。 实际上,如果b有一个falsy值,那么对于我来说, 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}"!`) } 

这不再给出参考错误。

b没有定义,因为没有这样的variables。 b:只是赋值给解构对象字面值的属性名称,它不声明variablesb 。 要获得一个,你需要使用两个解构步骤:

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