ES6解构嵌套的可选参数?

时间:2015-11-26 01:09:06

标签: javascript ecmascript-6

考虑以下ES6代码:

function foo({name, address: {street, postcode}}) {
  console.log(name, street, postcode);
}

foo({name: 'John', address: {street: 'Foo', postcode: 1234}});
foo({name: 'Bob'});

第一个呼叫按预期工作。不过,我希望address可选(streetpostcodeundefined),而不是抛出错误。这可能吗?

1 个答案:

答案 0 :(得分:5)

我找到了解决方案:

function foo({name, address: {street, postcode} = {}}) {
  console.log(name, street, postcode);
}