最近我在互联网上搜索一些可以处理废弃的 ajax/xhr 调用的代码。
这就是我发现的 https://stackoverflow.com/a/8841412/395910:
$.xhrPool = [];
$.ajaxSetup({
beforeSend: function (jqXHR) {
$.xhrPool.push(jqXHR);
},
complete: function (jqXHR) {
var i = $.xhrPool.indexOf(jqXHR);
if (i > -1)
$.xhrPool.splice(i, 1);
}
});
$.xhrPool.abortAll = function () {
$(this).each(function (i, jqXHR) {
jqXHR.abort();
$.xhrPool.splice(i, 1);// This is the line which makes me confused.
});
};
这段代码工作正常,但其中的一行让我感到困惑,我怀疑存在一些逻辑错误,但不知何故工作完美。
下面是让我困惑的部分,
$(this).each(function (i, jqXHR) {
$.xhrPool.splice(i, 1);
});
迭代 for 循环并获取第 i 个元素并将其从数组中删除。
现在,数组的总长度减少了,元素的索引也减少了,因为第一个成员被删除了。
然后在下一次迭代中,i 的值增加,因此被咳嗽的元素将不同(或不符合预期)。
例如,考虑 array = [1,2,3,4,5,6,7,8,9,10];
迭代1
array = [1,2,3,4,5,6,7,8,9,10]
i=0
removes 1
new array is [2,3,4,5,6,7,8,9,10]
迭代2
array = [2,3,4,5,6,7,8,9,10]
i=1
removes 3
new array is [2,4,5,6,7,8,9,10]
迭代3
array = [2,4,5,6,7,8,9,10]
i=2
removes 5
new array is [2,4,6,7,8,9,10]
迭代4
array = [2,4,6,7,8,9,10]
i=3
removes 7
new array is [2,4,6,8,9,10]
迭代5
array = [2,4,6,8,9,10]
i=4
removes 9
new array is [2,4,6,8,10]
迭代6
array = [2,4,6,8,10]
i=5
** 麻烦来了。
注意:我的计算机能够理解这段代码并正确执行它,但问题出在我的大脑上,我还没有准备好接受这部分:-(
我相信 $.each 是正确完成这项工作的人,但我仍然无法弄清楚它是如何实现的。