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 functi
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] );
}
};
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];
/* ... */
}
}
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.
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);