嵌套 jQuery 循环 - 如何更好地实现这一点?
我正在整理我继承的一个库,并遇到了这个小花絮:
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
是否是最有效的方法。
有什么想法吗?有什么建议吗?这种模式在多个地方重复出现,我很想知道如何更好地实现它。
I'm sprucing up a library I inherited and came across this little tidbit:
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;
}
});
});
The gist of what's happening above is that it is parsing the querystring and breaking up the elements into key-value pairs. Easy enough.
What happens after that is that it loops over that new array and then tests to see if the value of args
exists in the object literal value of self.affiliates.urlTag
. If so, it sets a cookie, sets gotAff
to true, and then returns false to kill the $.each
.
Something about this doesn't seem very efficient to me. I've been playing with a recursive function and I'm not quite there, and I'm not sure if I'm going down the wrong path. I'm not sure that killing the $.each
with a return false is the most efficient method either.
Any thoughts? Any tips? This sort of pattern is repeated in multiple places and I'd love to know how better to accomplish it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果我正确理解数据结构,这可能会更清晰一些:
If I understand the data structures correctly this might be a little cleaner:
我非常确定,无论它是什么 n² 操作,因为您必须遍历每个参数,并查看它是否存在于列表中。在这种情况下,你能做的最好的事情就是以某种方式澄清代码,但我不确定你是否有正确的函数在 jQuery 中执行此操作。
作为示例,我将在 MooTools 中执行此操作:
I'm pretty sure that no matter what it is an n² operation, because you have to go through each argument, and see if it is present in a list. The best you could do in this case is somehow clarify the code, but I'm not really sure you have the correct functions to do that within jQuery.
As an example, here's how I would do it in MooTools: