admin管理员组

文章数量:1136175

I'm trying to figure out if there's a way to use object destructuring of default parameters without worrying about the object being partially defined. Consider the following:

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

I'm trying to figure out if there's a way to use object destructuring of default parameters without worrying about the object being partially defined. Consider the following:

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

When I call this with {a: "qux"}, for instance, I see qux undefined in the console when what I really want is qux bar. Is there a way to achieve this without manually checking all the object's properties?

Share Improve this question edited Jul 6, 2016 at 7:16 Quentin Roy 7,8772 gold badges33 silver badges52 bronze badges asked Oct 26, 2014 at 21:27 user3019273user3019273 1,4332 gold badges9 silver badges4 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 263

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.

本文标签: javascriptES6 Object Destructuring Default ParametersStack Overflow