Looping through unknown number of array arguments

后端 未结 4 1224
暖寄归人
暖寄归人 2020-12-17 21:20

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

相关标签:
4条回答
  • 2020-12-17 21:42
    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] );
        }
    
    };
    
    0 讨论(0)
  • 2020-12-17 21:45

    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];
    
             /* ... */
        } 
    }
    
    0 讨论(0)
  • 2020-12-17 21:46

    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.

    0 讨论(0)
  • 2020-12-17 21:56

    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);
    
    0 讨论(0)
提交回复
热议问题