简体   繁体   English

无法使用拼接删除数组中的元素

[英]Unable to delete an element in array using splice

I'm iterating an array and based on a condition I want to delete the specific element from that array based on index(currently I use) . 我正在迭代一个数组,并根据条件想基于index从数组中删除特定元素(当前使用) Following is my code which is working perfectly as expected. 以下是我的代码,它可以按预期正常运行。

var todayWeekNo = new Date().getWeek();
$.each(arr, function (i, j) {
    var isEqual = todayWeekNo == new Date(j.Date).getWeek();
    if (isEqual) {
        delete arr[i];
    }
});

You can see this working fiddle 你可以看到这个工作的小提琴

While looking for a better approach, I came to know that 在寻找更好的方法时,我知道

Delete won't remove the element from the array it will only set the element as undefined. Delete不会从数组中删除元素,它只会将元素设置为undefined。

So I replaced delete arr[i]; 所以我替换了delete arr[i]; with arr.splice(i, 1); arr.splice(i, 1);

For first 2 iteration it was working fine, whereas it get stuck at the last iteration. 对于前两次迭代,它工作正常,而在最后一次迭代中卡住了。

Below is console message( jsfiddle ): 下面是控制台消息( jsfiddle ):

index0 arr: [object Object] (index):43
index1 arr: [object Object] (index):43
index2 arr: undefined (index):43
Uncaught TypeError: Cannot read property 'Date' of undefined

Please shed some light on this issue. 请阐明此问题。

If you are removing an element from the array, you need to make sure the index still matches: 如果要从数组中删除元素,则需要确保索引仍然匹配:

var arr = [0,1,2,3];
var index = 1;

arr[index] // 1
arr.splice(index,1);
index++;
arr[index] // 3 (2 was skipped, because arr[1] === 2 after splice)

Solution: 解:

for (var i=0; i<arr.length; i++) {
  if (cond) {
    arr.splice(i,1);
    i--;
  }
}

It looks like $.each() is not handling the modification of array 看起来$ .each()没有处理数组的修改

var todayWeekNo = new Date().getWeek();
for (var i = 0; i < arr.length;) {
    console.log("index" + i + " arr: " + arr[i]);

    var isEqual = todayWeekNo == new Date(arr[i].Date).getWeek();
    if (isEqual) {
        arr.splice(i, 1);
    } else {
        i++;
    }
}

Demo: Fiddle 演示: 小提琴

You are using loop to remove elements from array. 您正在使用循环从数组中删除元素。

Here, while you reach to i=2, array has only one element left. 在这里,当您达到i = 2时,数组仅剩一个元素。 So, it returns undefined. 因此,它返回未定义。

$.each is obvously not handling the modification of the array, i am not sure for (i < arr.length) does either, id rather try: $ .each显然不处理数组的修改,我不确定(i <arr.length)是否也这样做,id而是尝试:

for (i in arr) {
    console.log("index" + i + " arr: " + arr[i]);

    var isEqual = todayWeekNo == new Date(arr[i].Date).getWeek();
    if (isEqual) {
        arr.splice(i, 1);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM