Javascript ES6 对象解构默认参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26578167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ES6 Object Destructuring Default Parameters
提问by user3019273
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 undefinedin 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?
{a: "qux"}例如,当我用 调用它时,我会qux undefined在控制台中看到我真正想要的是qux bar. 有没有办法在不手动检查对象的所有属性的情况下实现这一点?
回答by Bergi
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.
这不仅限于函数参数,而且适用于每个解构表达式。

