Javascript函数和可选参数
我有两个几乎相同的JavaScript函数,用于启动jquery $ .get调用。 函数的参数被传递给被调用的脚本。
问题是一组调用需要另一个参数,而另一个不需要。
为了实现这一点,我使用了我提到的两个几乎相同的JavaScript函数。 他们来了:
function process(url, domid, domain, scan_id)
{
    $.get(url,
    {
        domain: domain,
        scan_id: scan_id
    },
    function(data)
    {
        $(domid).html(data);
    });
}
function process_type(url, domid, type, domain, scan_id)
{
    $.get(url,
    {
        domain: domain,
        type: type,
        scan_id: scan_id
    },
    function(data)
    {
        $(domid).html(data);
    });
}
正如你所看到的,第二个函数只接受一个叫'type'的附加参数,然后通过$ .get调用传递。
我想结合这两个函数,但我不知道如何可以选择包含第三个参数(数组/对象/无论它在{}(yes,javascript noob)),它是在$ .get中传递的。
编辑只是说....该死的,你们是好的。 :d
既然你所做的一切只是url和domid传递给$.get ,为什么不这样做呢? 
function process_type(url, domid, args) {
    $.get(url, args, function(data) {
        $(domid).html(data);
    });
}
// call it without type
process_type('myurl', 'domid', {domain:'..', scanid:'...'});
// call it with type
process_type('myurl', 'domid', {type: '..', domain:'..', scanid:'..'});
在javascript中的所有参数都是可选的,您可以使用函数内的参数数组来访问按照顺序传递的参数:
function myFunction(option1)
{
   var option2 = arguments[1];
   if(arguments[0] == option1)
      alert("Happy Day, Option1 = " + option1 + ", Option2 = " + option2);
}
myFunction("Hello", "World");
产生:快乐的一天,选项1 =你好,选项2 =世界
希望这可以说明如何使用参数数组来改进一些代码。
    function process_type(url, domid, domain, scan_id)
    {
            var myOptions = {
               domain: domain,
               scan_id: scan_id
            };
            if(arguments[4])
                myOptions["type"] = arguments[4];
            $.get(url, myOptions,
            function(data)
            {
                    $(domid).html(data);
            });
    }
然后你可以使用最后一个参数作为可选参数来调用它,如果参数被传递,那么它被使用,如果不被省略的话。
  另外,因为实际参数是可选的,所以你也可以将名称添加到函数定义的末尾,并且如果使用相同的arguments[4]而不是arguments[4]你会这样做if(type) myOptions["type"] = type; 
    function process_type(url, domid, domain, scan_id, type)
    {
            var myOptions = {
               domain: domain,
               scan_id: scan_id
            };
            if(type)
                myOptions["type"] = type;
            $.get(url, myOptions,
            function(data)
            {
                    $(domid).html(data);
            });
    }
此调用将包括类型
 process_type("xxx", "xxx", "xxx", "xxx", "xxx");
这个电话不会
 process_type("xxx", "xxx", "xxx", "xxx");
一些简单的方法来做到这一点
// 'b' is optional
// the 'null' value would be the default value
function Example1(a,b){
    b = b || null;
    // Some code here
}
function Example2(a,b){
    if(typeof b == 'undefined') b = null;
    // Some code here
}
function Example3(a,b){
    if(b === undefined) b=null;
    // Some code here
}
function Example4(a,b){
    if(!b) b=null;
    // Some code here
}
对于无限的参数,您可以使用数组'arguments',例如:
function ExampleArguments(){
    for(var i=0; i<arguments.length; i++){
            // Alert the current argument
            alert(arguments[i]);
    }
}
ExampleArguments('arg1',2,someVar);
