ES6对象破坏默认参数 [英] ES6 Object Destructuring Default Parameters

查看:150
本文介绍了ES6对象破坏默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想弄清楚是否有办法使用默认参数的对象解构,而不用担心对象被部分定义。请考虑以下内容:



 (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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆