将带有可选/默认属性的对象作为参数的函数? [英] Function that takes an object with optional/default properties as a parameter?

查看:112
本文介绍了将带有可选/默认属性的对象作为参数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解,使用ES6语法,可以创建一个将对象作为参数的函数,并且该参数可以具有默认值,如下所示:

I understand that, using ES6 syntax, a function can be made that takes an object as a parameter and that parameter can have a default value, like so:

function exampleFunction(objParam = {val1: 1, val2: 2}) {
    //...
}

如果我呼叫exampleFunction(),则会为objParam提供默认值.但是,如果我呼叫exampleFunction({val1: 3}),则objParam.val2undefined.这是有道理的,因为未应用默认设置.有什么方法可以使用ES6表示法来确保objParam.val2确实具有值?我知道我可以在函数中添加检查,但这会导致代码不一致,而我宁愿不这样做.

If I call exampleFunction(),objParam is given the default value. However, if I call exampleFunction({val1: 3}), objParam.val2 is undefined. This makes sense, because the default isn't being applied. Is there any way I can make sure that objParam.val2 does have a value, using the ES6 notation? I know I can add checks within the function, but that introduces inconsistency in the code and I'd rather not.

为澄清起见,这是一个更好的示例:

To clarify, here is a better example:

function exampleFunction(param = 0, objParam = {val1: 1, val2: 2}) {
    return objParam.val1;
}
exampleFunction(); // Returns 1 (this is good)
exampleFunction(1, {val1: 2}); // Returns 2 (this is good)
exampleFunction(1, {val2: 3}); // Returns undefined (I want it to return 1)

这是我目前拥有的东西,可以正常工作,但有点不雅致:

And here's what I currently have, which does work but is somewhat inelegant:

function exampleFunction(param = 0, objParam = {val1: 1, val2: 2}) {
    if(objParam.val1 === undefined) objParam.val1 = 1
    if(objParam.val2 === undefined) objParam.val2 = 2
    ...
}

推荐答案

您可以使用解构以提供默认值:

You can use destructuring in parameters to provide default values:

function exampleFunction({val1 = 1, val2 = 2} = {}) {
  console.log(val1, val2);
}
exampleFunction({val1: 5});
exampleFunction();

如果要将参数保留为对象,则可以使用Object.assign:

If you want to keep the parameter as an object, you can use Object.assign:

function exampleFunction(origParams = {}) {
  const objParam = Object.assign({ val1: 1, val2: 2 }, origParams);
  console.log(objParam.val1, objParam.val2);
}
exampleFunction({val1: 5});
exampleFunction();

这篇关于将带有可选/默认属性的对象作为参数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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