简体   繁体   English

我可以将 object 传递给将其字段作为参数的 function 吗?

[英]Can I pass an object into a function that takes its fields as parameters?

I have a function that looks somewhat similar to the following:我有一个 function 看起来有点类似于以下内容:

foobar: function(arg1, arg2, arg3, ... argN) {
   // execute function
   // return result
}

In reality, this function takes a lot of arguments.实际上,这个 function 需要很多arguments。 I am not allowed to change the content of this function or the way it's built.我不允许更改此 function 的内容或其构建方式。

I also have an object:我还有一个 object:

inputObj: {
   arg1: val1,
   arg2: val2,
   // ...
   argN: valN
}

where the fields of this object match the parameters of the function foobar exactly -- in other words, the fields are spelt the same, they're added to the object in the same order, etc.其中此 object 的字段与 function foobar 的参数完全匹配 - 换句话说,字段拼写相同,它们以相同的顺序添加到 object 等。

Does Javascript have an built-in function to either pass inputObj into the function foobar ? Javascript 是否具有内置的 function 以将inputObj传递到 function foobar Alternatively, does Javascript have an elegant way for me to split up the inputObj object into its contents such that the values are passed into the function according to their keys?或者,Javascript 是否有一种优雅的方式让我将inputObj object 拆分为其内容,以便根据它们的键将值传递到 function 中?

One possible solution, for example, could be:例如,一种可能的解决方案可能是:

const arg1 = inputObj['arg1'];
const arg2 = inputObj['arg2'];
// ...
const argN = inputObj['argN'];

foobar(arg1, arg2, ..., argN);

but I'm looking for a way to avoid writing out the whole code block as such to make it easier to read.但我正在寻找一种方法来避免写出整个代码块以使其更易于阅读。

Thanks in advance!!提前致谢!!

You can use destructuring.您可以使用解构。

const {arg1, arg2, ..., argN} = inputObj;
foobar(arg1, arg2, ..., argN);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将对象参数传递给反引号中的onclick函数 - How can I pass object parameters to the onclick function in backtick 如何访问对象变量的字段作为道具传递给它的子组件? - How can I access the object variable's fields to pass as the props to its child component? 我可以将参数传递给使用_.lodash去抖动的函数吗? - Can I pass parameters to a function debounced with _.lodash? 我可以将比较作为 function 参数传递吗? - Can I pass a comparison as a function parameters? 我可以在创建新的Web Workers对象时将参数传递给.js函数吗? - Can I pass parameters to .js function when I create the new Web Workers object? 你可以将参数传递给不接受参数的 React 钩子吗? - Can you pass parameters to a React hook that takes in no parameters? 我可以将一个函数的参数(req、res、next)传递给另一个函数吗? - Can I pass the parameters (req, res, next) of a function to another function? 如何在不使用函数参数的情况下将值传递给函数? - How can I pass a value into a function without using function parameters? 通过函数传递参数,但不传递执行结果 - Pass function with parameters, but not its execution result 使用JavaScript编写将2个单独的构造函数作为其参数的函数 - Writing a function that takes 2 separate constructor functions as its parameters using JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM