JQuery handles array out of index errors when $.each and array.splice(i) are kept together

泪湿孤枕 提交于 2019-12-04 16:56:40

The code "works", but is not doing what it is supposed to do. The method is called abortAll, and it does abort all XHRs, but only clears half of the array. It should really remove all items it aborts, which it doesn't.

jQuery each will take a copy of the array and iterate that, so i will still go from 0 to the last index in the (copied) array, even though elements are removed from the original array.

But it still goes wrong, because the splice acts on the original array, which moves elements to preceding indexes in that array. But i, on the other hand, keeps increasing, so one in two elements will survive the splice.

The abortAll could be corrected to this:

$.xhrPool.abortAll = function () {
    $(this).each(function (i, jqXHR) {
        jqXHR.abort();
        // the element to be deleted will always be at index 0 in the original array:
        $.xhrPool.splice(0, 1); 
    });
});

... but really, it can be done simply like this:

$.xhrPool.abortAll = function () {
    $(this).each(function (i, jqXHR) {
        jqXHR.abort();
    });
    $.xhrPool.length = 0;
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!