简体   繁体   中英

Call a function with an array which holds array of parameters instead of listing just arrays

Excuse the badly composed title, but what I'm asking is this:

Say you have a function like this:

function cartesianProductOf() {
      return Array.prototype.reduce.call(arguments, function(a, b) {
        var ret = [];
        a.forEach(function(a) {
          b.forEach(function(b) {
            ret.push(a.concat([b]));
          });
        });
        return ret;
      }, [[]]);
}

which is to be called like this:

cartesianProductOf([1, 2, 3], [4], [5, 6], ['a','b']);

The problem which I'm facing is that I make a dynamic array and I basically have an array which holds the arguments which should be sent to the function, like this:

var sets = [[1, 2, 3], [4], [5, 6], ['a','b']];

Now, of course, the call:

cartesianProductOf(sets);

will not work. True, I can modify the cartesianProductOf() function easily to this (only important part shown):

function cartesianProductOf() {
    return Array.prototype.reduce.call(arguments[0], function(a, b) {

But I'm wondering is there a way in javascript that I would call cartesianProductOf with sets variable, without having to change the code of cartesianProductOf to accept arguments[0]? Also, I would appreciate the change in title to the more appropriate one (as I've been searching for that keywords around the site, and clearly it's wrong as I couldn't find no relevant info).

As DCoder answered in the comment - I had to use apply method like this:

cartesianProductOf.apply(null, sets)

The difference between apply and call functions in JavaScript is well explained in this SO thread , and to quote:

The main difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly.

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