ES6对象解构默认参数

我试图找出是否有一种方法可以使用缺省参数的对象解构,而不用担心对象被部分定义。考虑以下几点:

(function test({a, b} = {a: "foo", b: "bar"}) {
console.log(a + " " + b);
})();

例如,当我用 {a: "qux"}调用它时,我在控制台中看到 qux undefined,而我真正想要的是 qux bar。有没有办法不用手动检查对象的所有属性就能做到这一点?

41524 次浏览

Yes. You can use "defaults" in destructuring as well:

(function test({a = "foo", b = "bar"} = {}) {
console.log(a + " " + b);
})();

This is not restricted to function parameters, but works in every destructuring expression.