10

渡されたいくつかの配列引数をループする方法を理解しようとしています。例:[1,2,3,4,5]、[3,4,5]、[5,6,7]関数に渡す場合、各引数内に関数ループをどのように設定しますか(任意渡すことができる配列の数)?

ここではforループを使用したいと思います。

4

4 に答える 4

19

これには引数を使用できます。

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

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

         /* ... */
    } 
}
于 2013-03-04T20:20:17.380 に答える
7

以下のように、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);
于 2017-05-15T12:47:06.613 に答える
2

使用している配列の数を含む組み込みのargumentsキーワードを使用します。lengthこれをベースとして、各アレイをループします。

于 2013-03-04T20:19:59.237 に答える
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] );
    }

};
于 2018-05-11T09:17:46.893 に答える