简体   繁体   中英

Javascript function(params) and function({ params }), one function two call types

Is there any way I could write a function in order to call it in both ways like this?

I know how to write both params structures in the function but I would like to know how to validate both params structures in a single function.

functionToCall(1, 'value', true);

and

functionToCall({
    param1: 1,
    param2: 'value',
    param3: true
});

You could check the first parameter, if it is an object and take a destruturing for the missing parameters.

This approach does not work if the first parameter is an object as a regular wanted type or if the type is any .

 function functionToCall(param1, param2, param3) { if (param1 && typeof param1 === 'object') { ({ param1, param2, param3 } = param1); } console.log(param1, param2, param3); } functionToCall(1, 'value', true); functionToCall({ param1: 1, param2: 'value', param3: true });

You can use rest params to get an array of parameters. If the length of the args array is 1, use object destructuring. If it's not 1 use array destructuring on the args array.

 const functionToCall = (...args) => { let param1, param2, param3; if (args.length === 1) ({ param1, param2, param3 } = args[0]); else ([param1, param2, param3] = args); console.log(param1, param2, param3); }; functionToCall(1, 'value', true); functionToCall({ param1: 1, param2: 'value', param3: true });

You can do like this for example

const functionToCall = () => {
  val [param1, param2, param3] = arguments.length == 1 
    ? Object.entries(arguments[0]).map(v => v[1]) 
    : arguments     
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM