JS调用函数,所有可能的参数都被置换

时间:2013-07-30 18:59:08

标签: javascript

考虑以下数组:

var array1 = [true, false];
var array2 = [1, 2];
var array3 = ["a", "b", "c"];

我想用所有参数组合调用我的函数 myFunc(arg1, arg2, arg3) 。但我想避免“预告”地狱。

是否有可能允许我的写功能,所以我可以称之为:

cartesianCall(array1, array2, array3, myFunc);

理想情况下是可变数组的数组(myFunc参数)?

编辑: 所以函数会被调用:

myFunc(true, 1, "a");
myFunc(true, 1, "b");
myFunc(true, 1, "c");
myFunc(true, 2, "a");
myFunc(true, 2, "b");
myFunc(true, 2, "c");
myFunc(false, 1, "a");
myFunc(false, 1, "b");
myFunc(false, 1, "c");
myFunc(false, 2, "a");
myFunc(false, 2, "b");
myFunc(false, 2, "c");

2 个答案:

答案 0 :(得分:5)

声明您没有参数的功能,并使用arguments关键字:

function cartesianCall() {
  for (var i = 0; i < arguments.length; i++) {
     // do something with arguments[i]
  }
}

答案 1 :(得分:3)

http://jsfiddle.net/trevordixon/zEqKy/

function cartesianCall(func, args) {
    var combos = allCombos.apply(this, args);

    for (var i = 0; i < combos.length; i++) {
        func.apply(null, combos[i]);
    }
}

function allCombos(first) {
    var isArray = toString.call(first) === "[object Array]";
    if (!isArray) first = [first]; // Convert non-array to an array with the value
                                   // as the only element
    else if (first.length === 0) first = [undefined]; // Convert empty array to an
                                                      // array with undefined as
                                                      // the only element

    if (arguments.length === 1) return first; // base case for recursion

    var result = [],
        rest = allCombos.apply(this, Array.prototype.slice.call(arguments, 1));

    for (var i = 0; i < first.length; i++) {
        for (var j = 0; j < rest.length; j++) {
            result.push([first[i]].concat(rest[j]));
        }
    }

    return result;
}

然后像这样使用它:

function printArgs() { console.log('Called with arguments:', arguments); }

cartesianCall(printArgs, [
    [true, false],
    undefined,
    [1, 2],
    [],
    'a string',
    ['a', 'b', 'c']
]);

打印:

Called with arguments: [true, undefined, 1, undefined, "a string", "a"] 
Called with arguments: [true, undefined, 1, undefined, "a string", "b"] 
Called with arguments: [true, undefined, 1, undefined, "a string", "c"] 
Called with arguments: [true, undefined, 2, undefined, "a string", "a"] 
Called with arguments: [true, undefined, 2, undefined, "a string", "b"] 
Called with arguments: [true, undefined, 2, undefined, "a string", "c"] 
Called with arguments: [false, undefined, 1, undefined, "a string", "a"] 
Called with arguments: [false, undefined, 1, undefined, "a string", "b"] 
Called with arguments: [false, undefined, 1, undefined, "a string", "c"] 
Called with arguments: [false, undefined, 2, undefined, "a string", "a"] 
Called with arguments: [false, undefined, 2, undefined, "a string", "b"] 
Called with arguments: [false, undefined, 2, undefined, "a string", "c"]

请注意,空数组的处理方式与undefined相同。