[英]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.