Passing an arbitrary number of function parameters in 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 a loop, but how do I send an “unknown” number of variables to a function?

+3
source share
5 answers

If you put all your arguments in an array (call it foo), you can call a function fnwith these arguments using the apply-function.

fn.apply(null, foo)

The first argument ( nullin this case) is that you want it to thisbe inside the called function. nullwill probably work for you.

+3
source

/ arguments:

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

[EDIT]

, , , () :

, . . .
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);
}

:

function f(arr, fn) {
    fn.apply(this, arr);
}
+2

arguments, , . IE

function blah() {
   console.log(arguments);
}

blah(1, 2); // [1, 2]
blah([1, 2], [3]); // [[1,2], [3]]
blah(1, [2, 3], "string"); // [1, [2, 3], "string"]
0

- arguments, , , (i, e , , , , arguments ).

0

arguments, .

function myConcat(separator) {  
   var result = ""; // initialize list  
   // iterate through arguments  
   for (var i = 1; i < arguments.length; i++) {  
      result += arguments[i] + separator;  
   }  
   return result;  
} 

See this article for a discussion of the variable number of arguments.

0
source

Source: https://habr.com/ru/post/1782798/