多次定义参数时获取 URL 参数值

Get URL parameter value when parameter is defined multiple times

本文关键字:参数 URL 获取 定义      更新时间:2023-09-26

我有以下网址:

products?feature_filters[]=&feature_filters[]=on&feature_filters[]=on

从这里我需要得到一个数组,如下所示:

var feature_filters = [1, 2] 

注意:正如MightyPork所指出的,这将是从零开始的......所以我需要拒绝0,并保留1和2。

我已经成功地使用此示例在定义一次URL参数时获取它们。但是,我无法解析由我的应用程序创建的这组参数。

您可以在链接答案中扩展 ,以相同的方式循环访问参数,但不仅仅是返回第一个匹配项,而是构建一个对象,其中每个属性都是查询字符串条目的名称,并包含一个其值的数组,基本上是数组的字典。

然后,对于特定键,您可以遍历其数组并查找设置了哪些索引:

// groups all parameters together into a dictionary-type object
function getUrlParameterGroups()
{
    var sPageURL = window.location.search.substring(1);
    var paramGroups = {};
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var paramParts = sURLVariables[i].split('=');
        var sParameterName = paramParts[0];
        // first time we've seen it - add a blank array
        if(!paramGroups.hasOwnProperty(sParameterName))
        {
            paramGroups[sParameterName] = [];
        }
        // ad to the array
        if(paramParts.length > 1)
        {
            paramGroups[sParameterName].push(paramParts[1]);
        }
        else
        {
            // handle not having an equals (eg y in x=1&y&z=2)
            paramGroups[sParameterName].push('');
        }
    }
    return paramGroups;
}
// gets which indices of the specified parameter have a value set
function getSetUrlParameters(sParameterName)
{
    var arr = getUrlParameterGroups()[sParameterName];
    return arr.reduce(function(previousValue, currentValue, index) {
        if(currentValue != '') { // or if(currentValue == 'on')
            previousValue.push(index);
        }
        return previousValue;
    }, []);
}
var result = getSetUrlParameters('feature_filters[]');
console.log(result);

工作小提琴