Function that takes an object with optional/default properties as a parameter?

一个人想着一个人 提交于 2020-02-14 06:50:33

问题


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}) {
    //...
}

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.

Edit: 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
    ...
}

回答1:


You can use destructuring in parameters to provide default values:

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

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



回答2:


Probably not as clean as you're looking for, but you can do this instead

function exampleFunction(objParams) {
  const defParams = { val1: 1, val2: 2 };

  const finalParams = { ...defParams, ...objParams }
  // final params takes the default params and overwrites any common properties with incoming params

  // ...
}


来源:https://stackoverflow.com/questions/50237260/function-that-takes-an-object-with-optional-default-properties-as-a-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!