简体   繁体   English

用包含参数数组的数组调用函数,而不是仅列出数组

[英]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): 没错,我可以很容易地对此修改cartesianProductOf()函数(仅显示重要部分):

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]? 但是我想知道在javascript中是否有一种方法可以调用具有sets变量的cartesianProductOf ,而不必更改cartesianProductOf的代码以接受参数[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: 正如DCoder在评论中回答的那样-我必须使用如下的apply方法:

cartesianProductOf.apply(null, sets)

The difference between apply and call functions in JavaScript is well explained in this SO thread , and to quote: 这个SO线程很好地解释了JavaScript中applycall函数之间的区别,并引用:

The main difference is that apply lets you invoke the function with arguments as an array; 主要区别在于apply允许您将参数作为数组调用函数; call requires the parameters be listed explicitly. 调用需要显式列出参数。

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

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