简体   繁体   English

ES6对象解析默认参数

[英]ES6 Object Destructuring Default Parameters

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 . 例如,当我用{a: "qux"}调用它时,我在控制台中看到qux undefined ,而我真正想要的是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. 这不仅限于函数参数,而是适用于每个解构表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM