ES6 对象解构默认参数 [英] ES6 Object Destructuring Default Parameters

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

问题描述

我想弄清楚是否有一种方法可以使用默认参数的对象解构,而不必担心对象被部分定义.考虑以下几点:

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);
})();

例如,当我用 {a: "qux"} 调用它时,我在控制台中看到 qux undefined 而我真正想要的是 qux条形.有没有办法在不手动检查对象的所有属性的情况下实现这一点?

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天全站免登陆