Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through unknown number of array arguments

Tags:

javascript

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.

like image 487
swaggyP Avatar asked Mar 04 '13 20:03

swaggyP


1 Answers

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);
like image 154
Banoona Avatar answered Sep 21 '22 23:09

Banoona