【问题标题】:Nested jQuery loops - how can this be better accomplished?嵌套的 jQuery 循环 - 如何更好地完成?
【发布时间】:2011-03-18 04:01:11
【问题描述】:

我正在整理一个我继承的图书馆,并偶然发现了这个小花絮:

queries = urlParams.query.split("&");

// Split URL Queries
$.each(queries, function (i, val) {
    val = val.split("=");
    args[val[0]] = val[1];  //Assign query args into args object using their name (ie: test=123) as the key
});

// Loop through arguments
$.each(args, function (i, val) {
// Loop through affiliates to compare url arguments against those of the affiliates
    $.each(self.affiliates, function (inc, value) {
        if (value.urlTag === i) {
        self.setAffiliateCookies(i, val, 1);    //Set affiliate cookies
            gotAff = true;
            return false;
        }
    });
});

上面发生的事情的要点是它正在解析查询字符串并将元素分解为键值对。很简单。

之后发生的事情是它循环遍历该新数组,然后测试args 的值是否存在于self.affiliates.urlTag 的对象字面值中。如果是这样,它会设置一个 cookie,将 gotAff 设置为 true,然后返回 false 以终止 $.each

这对我来说似乎不是很有效。我一直在玩递归函数,但我并不完全在那里,我不确定我是否走错了路。我不确定用 return false 杀死 $.each 是不是最有效的方法。

有什么想法吗?有小费吗?这种模式在多个地方重复出现,我很想知道如何更好地完成它。

【问题讨论】:

  • 与您的问题无关,但val = val.split("="); 并不总是给您正确的值,因为?key=value=abc&key2=123 仍然有效。虽然在大多数情况下这可能无关紧要。

标签: javascript jquery recursion nested-loops


【解决方案1】:

如果我正确理解数据结构,这可能会更简洁:

$.each(self.affiliates, function (inc, value) {
    if (args.hasOwnProperty(value.urlTag)) {
        self.setAffiliateCookies(value.urlTag, args[value.urlTag], 1);    //Set affiliate cookies
        gotAff = true;
        return false;
    }
});

【讨论】:

    【解决方案2】:

    我很确定无论它是什么 n² 操作,因为您必须检查每个参数,并查看它是否存在于列表中。在这种情况下,您能做的最好的事情就是以某种方式澄清代码,但我不确定您是否有正确的函数在 jQuery 中执行此操作。

    举个例子,下面是我在 MooTools 中的做法:

    // Create array of affiliate URL tags.
    var affiliateURLs = self.affiliates.map(function(affiliate) {
        return affiliate.urlTag;
    });
    
    // Filter args list to those with affiliates.
    // This is the n² part.
    var matchedArgs = Object.filter(args, function(arg, argURL) {
        return affiliateURLs.contains(argURL);
    });
    
    // Create cookie for each matched arg.
    Object.each(matchedArgs, function(arg, argURL) {
        self.setAffiliateCookies(argURL, arg, 1);
    });
    
    // Note that gotAff is simply
    // (Object.getLength(matchedArgs) > 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 2021-08-09
      • 2014-03-05
      • 2018-04-15
      相关资源
      最近更新 更多