Javascript中的可选参数如何工作? [英] How do optional parameters in Javascript work?

查看:39
本文介绍了Javascript中的可选参数如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

摘自w3在线教程:

$("button").click(function(){
    $("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
        if(statusTxt == "success")
            alert("External content loaded successfully!");
        if(statusTxt == "error")
            alert("Error: " + xhr.status + ": " + xhr.statusText);
    });
});

函数调用如何知道正在传递哪些参数,例如说您仅传递 statusTxt xhr 或只想传递 xhr ?

How does the function call know which parameters are passing, like say you only pass in statusTxt and xhr or you only want to pass in xhr?

请对我说些轻松:)这是我有史以来第一个问题

Please go easy on me guys :) this is my first question ever

推荐答案

简单地,它没有,因为它从左到右分配了从函数调用中传递的每个参数.假设您具有从您那里复制来的此功能:

Simply, it doesn't, because it assigns each parameter you pass on from your fnction call from left to right. Let's say you have this function, copied from you:

function someFunction(responseTxt, statusTxt, xhr){
    if(statusTxt == "success")
        alert("External content loaded successfully!");
    if(statusTxt == "error")
        alert("Error: " + xhr.status + ": " + xhr.statusText);
}

,并且您希望在调用此函数时传递变量 statusTxt :成功"和 xhr :your_xhr的值.如果您这样调用函数:

and you want to pass values for variables statusTxt: "success" and xhr: your_xhr when you call this function. If you called the function like this:

someFunction("success",your_xhr);

someFunction("success", your_xhr);

这意味着将成功"分配给参数 responseTxt ,将your_xhr分配给 statusTxt .

this means "success" will be assigned to the parameter responseTxt and your_xhr to statusTxt.

通常,您可以将responseTxt设置为 null ,然后将其余的设置为所需的值,例如:

Normally, you could just set responseTxt to null and set the rest to what you want, for example:

someFunction(null,成功",your_xhr);

someFunction(null, "success", your_xhr);

或在函数定义中使用对象文字.这是一个示例:

or use an object literal in your function definition. Here's an example:

function someFunction(options){
    if(options.statusTxt == "success")
        alert("External content loaded successfully!");
    if(options.statusTxt == "error")
        alert("Error: " + options.xhr.status + ": " + options.xhr.statusText);
}

,您的函数调用将如下所示:

and your function call would look like this:

someFunction({statusTxt:"success",xhr:your_xhr});

someFunction({statusTxt: "success", xhr: your_xhr});

当然,您需要检查responseTxt是否为 未定义 ,以防不使用它.

Of course you need to check if responseTxt is undefined in case you don't use it.

希望这会有所帮助.

这篇关于Javascript中的可选参数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆