javascript 循环遍历未知数量的数组参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15210312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:52:20  来源:igfitidea点击:

Looping through unknown number of array arguments

javascript

提问by swaggyP

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) ?

我想弄清楚如何遍历传递的几个数组参数。例如:[1,2,3,4,5],[3,4,5],[5,6,7] 如果我将它传递给一个函数,我将如何在每个参数(任何可以传递多少个数组)?

I want to use a for loop here.

我想在这里使用 for 循环。

回答by James McLaughlin

You can use argumentsfor 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];

         /* ... */
    } 
}

回答by Banoona

Use forEach, as below:

使用 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);

回答by Darren

Use the built in argumentskeyword which will contain the lengthof how many arrays you have. Use that as a basis to loop through each array.

使用内置arguments关键字,它将包含length您拥有的数组数量。以此为基础循环遍历每个数组。

回答by David

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] );
    }

};