10

I am trying to figure out how to loop through several array arguments passed. For example: [1,2,3,4,5],[3,4,5],[5,6,7] If I pass it to a function, how would I have a function loop inside each argument (any number of arrays can be passed) ?

I want to use a for loop here.

j08691
  • 204,283
  • 31
  • 260
  • 272
swaggyP
  • 355
  • 1
  • 5
  • 18
  • within the function you'd iterate over `arguments`, and for each argument, you'd iterate over the array. – zzzzBov Mar 04 '13 at 20:19
  • possible duplicate of [JavaScript variable number of arguments to function](http://stackoverflow.com/questions/2141520/javascript-variable-number-of-arguments-to-function) – jbabey Mar 04 '13 at 20:19
  • var args = arguments; for(i = 0; i < args.length,i++) var l = args[i].length; – swaggyP Mar 04 '13 at 20:20

4 Answers4

19

You can use arguments for this:

for(var arg = 0; arg < arguments.length; ++ arg)
{
    var arr = arguments[arg];

    for(var i = 0; i < arr.length; ++ i)
    {
         var element = arr[i];

         /* ... */
    } 
}
James M
  • 18,506
  • 3
  • 48
  • 56
7

Use forEach, as below:

'use strict';

    function doSomething(p1, p2) {
        var args = Array.prototype.slice.call(arguments);
        args.forEach(function(element) {
            console.log(element);
        }, this);
    }

    doSomething(1);
    doSomething(1, 2);
Rafael Herscovici
  • 16,558
  • 19
  • 65
  • 93
Banoona
  • 1,470
  • 3
  • 18
  • 32
2

Use the built in arguments keyword which will contain the length of how many arrays you have. Use that as a basis to loop through each array.

Darren
  • 68,902
  • 24
  • 138
  • 144
0
function loopThroughArguments(){
    // It is always good to declare things at the top of a function, 
    // to quicken the lookup!
    var i = 0,
        len = arguments.length;

    // Notice that the for statement is missing the initialization.
    // The initialization is already defined, 
    // so no need to keep defining for each iteration.
    for( ; i < len; i += 1 ){

        // now you can perform operations on each argument,
        // including checking for the arguments type,
        // and even loop through arguments[i] if it's an array!
        // In this particular case, each argument is logged in the console.
        console.log( arguments[i] );
    }

};
David
  • 1
  • 1
  • 2