首页 > 解决方案 > 将多个参数传递给 Javascript 函数

问题描述

我有一个功能如下:

//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. 如果您对如何完成有建议,那就太好了。这会有很大帮助。

标签: javascripthtmlarraysajax

解决方案


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

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);

推荐阅读