Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arbitrary number of parameter to a function in javascript

Tags:

javascript

I would like to write a javascript function that works something like this...

f([["a"]], function(e){alert(e);});
// results in alert("a");

f([["a"], ["b"]], function(e1,e2){alert(e1 + ":" + e2);});
//results in alert("a:b");

f([["a", "b"], ["c"]], function(e1,e2){alert(e1 + ":" + e2);});
//results in alert("a:c");alert("b:c");

I can think of a recursive solution for the looping, but how do I send a "unknown" number of variables to a function?

like image 842
mncl Avatar asked Nov 29 '25 21:11

mncl


2 Answers

If you put all your arguments into an array (lets call it foo), you can call a function fn with those arguments by using the apply-function.

fn.apply(null, foo)

The first argument (null in this case) is whatever you want this to be inside of the called function. null will probably work for you.

like image 121
Jakob Avatar answered Dec 01 '25 11:12

Jakob


According to this page, you can access any/all arguments using the arguments variable:

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

[EDIT]

Now that I understand what you're trying to do, here's a (dirty) way to do it:

Seriously, don't do it this way. It's horrible. Puppies will die.

function f(arr, fn) {
    var s = "fn(";
    for( var i = 0; i < arr.length; i++ ) {
        //you can implement your recursive code here if you like; I'm just doing the base cases
        s += arr[i];
        if(i+1 < arr.length) {
            s += ",";
        }
    }
    s += ");";
    eval(s);
}

And for a cleaner way:

function f(arr, fn) {
    fn.apply(this, arr);
}
like image 22
NickAldwin Avatar answered Dec 01 '25 10:12

NickAldwin