简体   繁体   中英

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

_.intersection(*arrays)

I understand I can use the function like so:

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

and get ['a'] back.

I have a variable amount of arrays however, so I want to do something like this:

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:

 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 .

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