我试图弄清楚如何遍历传递的几个数组参数。例如: [1,2,3,4,5],[3,4,5],[5,6,7] 如果我将它传递给一个函数,我将如何在每个参数内部都有一个函数循环(任何可以传递的数组数量)?
我想在这里使用 for 循环。
我试图弄清楚如何遍历传递的几个数组参数。例如: [1,2,3,4,5],[3,4,5],[5,6,7] 如果我将它传递给一个函数,我将如何在每个参数内部都有一个函数循环(任何可以传递的数组数量)?
我想在这里使用 for 循环。
您可以为此使用参数:
for(var arg = 0; arg < arguments.length; ++ arg)
{
    var arr = arguments[arg];
    for(var i = 0; i < arr.length; ++ i)
    {
         var element = arr[i];
         /* ... */
    } 
}
使用 forEach,如下:
'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);
使用内置arguments关键字,该关键字将包含length您拥有的数组数量。以此为基础循环遍历每个数组。
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] );
    }
};