Destructing optional function parameters

时间:2018-09-18 20:32:06

标签: javascript ecmascript-6

Scratching my head trying to get this optimal. Say I have a function that takes an object as a parameter and destruct it like so:

myfunc = (options = {a:true, b:true, c:true}) => {...}

By default a b and c are true. But say I call myfunc and want b to be false:

myfunc({b:false})

well now options.b === false, but the values for a and c are gone. Is there away I can accomplish this without having to pass in a copy of the default values?

I tried something weird like

myfunc = (options = Object.assign({a:true, b:true, c:true}, options)) =>{}

but that's certainly not right.

2 个答案:

答案 0 :(得分:6)

您可以在不使用option的情况下使用具有默认值的所需属性的解构的默认对象。然后使用速记属性创建一个新的。

对于其他对象,您可以将其休息属性与更新的或babeljs一起使用。

var myfunc = ({ a = true, b = true, c = true, ...rest } = {}) => {
        const option = { a, b, c, ...rest };
        console.log(option);
    };

myfunc();             // take {} as default and the default values inside of the object
myfunc({ b: false }); // take b and default values
myfunc({ foo: 42 });  // take foo and all default values
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

您可以在解构语句中传递默认值:

'100'

显然,缺点是无法整体参考这些选项。 因此,以myFunc = ({a=true, b=true, c=true}) 作为参数并在函数体中进行分解可能是更好的选择:

options