javascript 允许javascript函数接受任意数量的参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3583044/
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-25 01:37:11  来源:igfitidea点击:

Allowing javascript function to accept any number of arguments

javascriptjqueryfunction

提问by RyanP13

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() {
    function icisDashBox(colorElem, thisWidth, thisHeight, completeCallBack) {
        $(colorElem).colorbox({
        transition: 'none',
        innerWidth: thisWidth,
        innerHeight: thisHeight,
        opacity: '0.5',
        onOpen: function() { 

        },
        onLoad: function() { 

        },
        onComplete:function() { 
            $('#cboxLoadedContent').wrap('<div id="icis_dialog_msg" />'); 

            completeCallBack();

        },
        onCleanup: function() { 

        },      
        onClosed: function() {
            $('#cboxLoadedContent').unwrap(); 
        }
    });
}

icisDashBox('.example9', '500', '500', completeFunction);

function completeFunction() {

    var fooClass = $("#colorbox").addClass("FOO");

    var barClass = $("#colorbox").addClass("BAR");

    var ajaxCnt = $.ajax({
        type: "GET",
        url: "http://www.payso.me.uk",
        dataType: "html",
        success: function(data) {
            $("#colorbox").addClass("AJAX SUCCESS");
        }
    });

    return {
        x : fooClass,
        y : barClass,
        z : ajaxCnt                         
    };
}

So in an ideal world my function would look like this without explicitly declaring any arguments:

因此,在理想的世界中,我的函数看起来像这样,无需明确声明任何参数:

function icisDashBox() { function code here }

Is this possible? Also if the arguments are not defined how do i handle that?

这可能吗?另外,如果未定义参数,我该如何处理?

For example if one call to the function has several callbacks defined and another only has one is there a way of handling the lack of presence of callbacks.

例如,如果对函数的一个调用定义了多个回调,而另一个只有一个,那么有没有一种方法可以处理不存在回调的情况。

Cheers,

干杯,

:)

:)

回答by Nick Craver

You can use the keyword argumentswhich is an array of the passed arguments, like this:

您可以使用作为arguments传递参数数组的关键字,如下所示:

function myFunc() {
   if(arguments.length > 0)     //be sure to check if there are any...
     var arg1 = arguments[0];
}

However, a much better approach is to accept an object, e.g.:

但是,更好的方法是接受一个对象,例如:

function myFunc(settings) {
   settings = settings || {};   //in case it was called as just: myfunc()
   var something = settings.something || "default value";
}

You'd call it like this:

你会这样称呼它:

myFunc({ something: "value", somethingElse: "otherValue" });

This approach allows you to accept any number of arguments as well, but also have any optional, without a bunch of myFunc(null, null, null, "value")type calls to provide only the parameter you want, plus they're named making this muchmore maintainable IMO. Here's an edited version of the plugin to demonstrate this.

这种方法也允许你接受任意数量的参数,但也有任何可选的,没有一堆myFunc(null, null, null, "value")类型调用来只提供你想要的参数,而且它们的命名使得这个易于维护 IMO。 这是插件的编辑版本来演示这一点

回答by rochal

Use argumentsvariable.

使用参数变量。

function TestMe()
{
   var args = arguments;

   for (var a in args)
   {
     alert(args[a]);
   }
}

Now you can pass any number of arguments to TestMefunction:

现在您可以将任意数量的参数传递给TestMe函数:

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

etc.

等等。

回答by Lasithds

Thanks to the spread operator now you can do something like this

多亏了传播操作符,你现在可以做这样的事情

function myFunction(...params) {
  console.log(...params);
}

myFunction('Many arguments', 1, {two: 3}, ["four", 5]);

// to access one by one
function oneByOne(...params) {
  params.map(param => {
   console.log(param);   
  });
}

oneByOne('Many arguments', 1, {two: 3}, ["four", 5]);

回答by Youssef

Yes this is possible, here's an example :

是的,这是可能的,这是一个例子:

function myfunct()
{

  var arguments = myfunct.arguments;

  for (var i = 0; i < arguments.length; i++)
        {

                alert("Argument " + i + " value = " + arguments[i]);

            }

}

You can call this fonction by any number of arguments :

您可以通过任意数量的参数调用此函数:

myfunct("foo");

myfunct("foo","bar");

回答by db998

In more recent times you can now make use or the spread and rest operators as detailed here - Pass unknown number of arguments into javascript function

最近,您现在可以使用此处详述的传播和剩余运算符 - 将未知数量的参数传递给 javascript 函数