考虑以下ES6代码:
function foo({name, address: {street, postcode}}) {
console.log(name, street, postcode);
}
foo({name: 'John', address: {street: 'Foo', postcode: 1234}});
foo({name: 'Bob'});
第一个呼叫按预期工作。不过,我希望address
可选(street
和postcode
为undefined
),而不是抛出错误。这可能吗?
答案 0 :(得分:5)
我找到了解决方案:
function foo({name, address: {street, postcode} = {}}) {
console.log(name, street, postcode);
}