Allowing javascript function to accept any number of arguments

后端 未结 6 1816
难免孤独
难免孤独 2020-12-29 05:28

I would like the below function to be more flexible and accept multiple callbacks to other functions if they are defined in the arguments.

$(function() {
            


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-29 06:02

    Use arguments variable.

    function TestMe()
    {
       var args = arguments;
    
       for (var a in args)
       {
         alert(args[a]);
       }
    }
    

    Now you can pass any number of arguments to TestMe function:

    TestMe(1);
    TestMe(1,2,3);
    TestMe(1,2,3,4,5,6);
    TestMe.apply(this, [1,2,3,4,5]); 
    

    etc.

提交回复
热议问题