Unlimited arguments in a JavaScript function

前端 未结 9 1859

Can a JavaScript function take unlimited arguments? Something like this:

testArray(1, 2, 3, 4, 5...);

I am trying:

var arr          


        
9条回答
  •  再見小時候
    2020-12-07 18:21

    You can also just "cast" it, saving you the ugly loop:

    var getArguments = function() {
        return arguments;
    };
    
    var foo = getArguments(1,2,3,4);
    
    // console.log(foo.slice()); => TypeError: foo.slice is not a function
    
    var foo = Object.values(foo); 
    
    console.log(foo); // => [ 1, 2, 3, 4 ]
    
    foo.push(5);
    
    console.log(foo); // => [ 1, 2, 3, 4, 5 ]
    

提交回复
热议问题