简体   繁体   中英

Unable to remove array in javascript

I have an of object, contains 5 element.

Now I loop through the to delete elements of which match with my condition.

for(var i = 0; i < items.length ; i++){
  console.log(i + '-'); //the result is 3-4
  if(_today.getTime() - items[i].timestamp >= numDay * ONE_DAY){
     console.log(i); //the result is 3
     items.splice(i,1);
  }
}

Sample of my array :

[{"DepartmentID":56,"CategoryID":117,"BrandID":19,"ID":707},
 {"DepartmentID":56,"CategoryID":117,"BrandID":19,"ID":708},
 {"DepartmentID":56,"CategoryID":117,"BrandID":19,"ID":709},
 {"DepartmentID":56,"CategoryID":117,"BrandID":19,"ID":710},
 {"DepartmentID":56,"CategoryID":117,"BrandID":19,"ID":711}]

The delete only one element in this for loop . Is it because of the index of problem and how could I delete n elements of the that match the condition in this loop?

Any help would be much appreciated, thank you..

When you modify an arrays size while looping it, you need to adjust your current index as you go. In your case whenever you splice off an item you need to --i; . This will back up your index by one and not cause your loop to skip an item.

This is because you using items.length to decide iterations for your loop and deleting it inside loop which changes length on every iteration you delete. You could manipulate copy of array inside loop instead then replace it in orignal one.

Something like this

var temp = items;

for(var i = 0; i < items.length ; i++){
  console.log(i + '-'); //the result is 3-4
  if(_today.getTime() - items[i].timestamp >= numDay * ONE_DAY){
     console.log(i); //the result is 3
     temp.splice(i,1);
  }
}

items= temp;

First, find the index of the element you want to remove:

var array = [2, 5, 9];
var index = array.indexOf(5);

Then remove it with splice:

if (index > -1) {
    array.splice(index, 1);
}

The second parameter of splice is the number of elements to remove. Note, splice modifies the array in place and returns an array with the elements you remove

I found this solution in one of the jQuery plugins' source. items.splice(i--, 1); seems much simpler. This works only in case of deleting one item at a time from the array

for(var i = 0; i < items.length ; i++){
  if(_today.getTime() - items[i].timestamp >= numDay * ONE_DAY){
     items.splice(i--, 1);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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