使用 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"!
- 如何定义
b
? - 如果
a.b
设置为非虚假值,我如何调用mandatory
并抛出我自己的错误?
最佳答案
找到了解决方案。实际上,在 b
具有虚假值的情况下进行 mandatory
函数调用对我来说是没有意义的。如果c
或d
确实存在,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}"!`)
}
这不再给出引用错误。
关于javascript - 使用默认值解构嵌套对象,包括 Node ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41686211/