如何使用 ES6 中的所有默认值解构选项参数? [英] How to destructure option argument with all default values in ES6?

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

问题描述

我在 babel 编译器中使用 ES6 特性.我有一个将选项对象作为参数的函数:

I use ES6 features with babel compiler. I have a function which takes option object as an argument:

function myFunction({ option1 = true, option2 = 'whatever' }) {
    console.log(option1, option2);
    // do something...
}

当我调用它时,会发生解构并且一切正常.大多数时候我想用默认选项调用它,所以我这样做:

When I call it, destructuring happens and everything works well. I want to call it with default options most of the time, so I do:

myFunction({}); // true 'whatever'

但看起来有点奇怪.打电话会更干净:

but it looks little bit strange. It would much more cleaner just call:

myFunction(); // TypeError: Cannot read property 'option1' of undefined

有可能吗?

推荐答案

是的,您只需为完整的参数提供一个默认值:

Yes, you just have to provide a default value for the complete argument:

function myFunction({option1 = true, option2 = 'whatever'} = {}) {
//                                                         ^^^^
    console.log(option1, option2);
    // do something...
}

这篇关于如何使用 ES6 中的所有默认值解构选项参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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