简体   繁体   English

将可变数量的参数传递给看起来像“function(*x)”的 function JavaScript

[英]Passing in variable amount of parameters to a function that looks like “function(*x)” JavaScript

I can't seem to find an answer to this question because I don't really know what this is called, if there's a solution already point me there.我似乎找不到这个问题的答案,因为我真的不知道这叫什么,如果有解决方案已经指向我那里。

I'm trying to use this from underscore.js我正在尝试从underscore.js中使用它

_.intersection(*arrays)

I understand I can use the function like so:我知道我可以像这样使用 function:

var intersection = _.intersection(['a','b'], ['a','c'])

and get ['a'] back.并得到['a']回来。

I have a variable amount of arrays however, so I want to do something like this:但是,我有可变数量的 arrays,所以我想做这样的事情:

var intersection = _.intersection(array for array in my_arrays)

I understand I could do this:我知道我可以这样做:

var intersection = my_arrays[0];
my_arrays.forEach(arr => intersection = _.intersection(intersection, arr) )

But that doesn't seem clean.但这似乎并不干净。 How can this be done?如何才能做到这一点? Thanks.谢谢。

Most modern browsers support ES6 so you can use the spread operator to do this:大多数现代浏览器都支持 ES6,因此您可以使用扩展运算符来执行此操作:

 const my_arrays = [[1, 2], [1, 3, 4], [1, 5, 6, 7]]; dummy_intersection(...my_arrays); function dummy_intersection(...arrays) { console.log(arrays[0]); }

On a side note, it's generally considered a better idea to use lodash than underscore .附带说明一下,通常认为使用 lodash 比使用 underscore 更好

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

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