【问题标题】:Passing multiple parameters to a Javascript function将多个参数传递给 Javascript 函数
【发布时间】:2020-05-01 16:34:27
【问题描述】:

我有一个函数如下:

//Calling the Function with one Parameter
responses(baseURL);

//Function Definition
function responses(baseURL) {
    $.ajax({
        url: baseURL,
        type: "get",
        cache: false,
        headers: {
            'Content-Type': 'application/json'
        },
        success: function (data) {
            console.log(data.features.length);
            for (var i = 0; i < data.features.length; i++) {
                if (taxArrayT1.indexOf(data.features[i].properties.taxon_id) == -1) {
                    taxArrayT1.push(data.features[i].properties.taxon_id);
                }
            }
            console.log("In the Invertebrate Animals Section 1");
            console.log(taxArrayT1.length);
        }
    })
}

现在我倾向于重复自己,因为当我使用相同的功能访问不同的服务时。我知道如何将基本 URL 作为参数传递。在这个例子中还有一个数组,taxArrayT1。每次使用不同的输入时,此数组都会更改,例如 taxArrayT2。如果您对如何完成有建议,那就太好了。这会有很大帮助。

【问题讨论】:

  • 你可以定义你的函数为function responses(baseURL, taxArray){...}

标签: javascript html arrays ajax


【解决方案1】:

如果我正确理解您要执行的操作,那么您可以将数组添加为第二个参数。像这样:

function responses(baseURL, taxArray) {
    $.ajax({
        url: baseURL,
        type: "get",
        cache: false,
        headers: {
            'Content-Type': 'application/json'
        },
        success: function (data) {
            console.log(data.features.length);
            for (var i = 0; i < data.features.length; i++) {
                if (taxArray.indexOf(data.features[i].properties.taxon_id) == -1) {
                    taxArray.push(data.features[i].properties.taxon_id);
                }
            }
            console.log("In the Invertebrate Animals Section 1");
            console.log(taxArray.length);
        }
    })
}

服务调用将如下所示:

responses(url1, taxArrayT1);
responses(url2, taxArrayT1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 2010-11-03
    • 2011-10-02
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多