ES6对象破坏默认参数 [英] ES6 Object Destructuring Default Parameters
问题描述
我想弄清楚是否有办法使用默认参数的对象解构,而不用担心对象被部分定义。请考虑以下内容:
(function test({a,b} = { a:foo,b:bar}){console.log(a ++ b);})();
/ div>
例如,当我以 {a:qux}
code> qux undefined 在控制台中,我真正想要的是 qux bar
。有没有手段来检查所有对象的属性?
是的。您可以在解构中使用defaults:
(function test {a =foo,b =bar} = {}){console.log(a ++ b);})();
/ div>
这不限于函数参数,而是适用于每个解构表达式。
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?
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.
这篇关于ES6对象破坏默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!