简体   繁体   中英

jQuery iterate through loop delete elements

I have a javascript array of objects: each object contains key/value pairs. I'm trying to iterate through this array, and delete any object whose value for a particular key (say "Industry") fails to match a given value. Here is my code, for some reason it's not looping through the whole array, and I think it has something to do with the fact that when I delete an item the loop counter is botched somehow:

var industry = 'testing';
var i = 0;
for (i = 0; i < assets_results.length; i++) {

    var asset = assets_results[i];
    var asset_industry = asset['industry'];
    if (industry != asset_industry) { assets_results.splice(i,1); }

}   

Any ideas? Thanks in advance.

This is because when you splice one element, the size of array decreases by one. All elements after the splice shift one position to the beginning of the array and fills the space of spliced one. So the code misses one element.Try this code.

var industry = 'testing';
var i = 0;
for (i = 0; i < assets_results.length; i++) {

    var asset = assets_results[i];
    var asset_industry = asset['industry'];
    if (industry != asset_industry) { 
              assets_results.splice(i,1); 
              i--;
    }

} 

splice removes an element from an array and resizes it :

var arra = ['A', 'B', 'C', 'D'];
arr.splice(1,2); // -> ['A', 'D'];

Which means that you should not increment i when you splice, because you skip the next element. splicing will make of the i + 2 element the i + 1 element.

var industry = 'testing';

for (var i = 0, max = assets_results.length; i < max; ) { // Accessing a property is expensive.
    if (industry != assets_results[i]['industry']) {
        assets_results.splice(i,1);
    } else {
        ++i;
    }
}   

This is a common problem when modifying an object while iterating through it. The best way to avoid this problem is, rather than deleting pairs from the existing array if they fail the test, to create a new array and only add pairs if they pass the test.

var industry = 'testing';
var i = 0;
var asset_results_filtered = [];

for (i = 0; i < assets_results.length; i++) {
    if (industry == assets_results[i]) {
        asset_results_filtered.push(assets_results[i]);
    }
}

EDIT: Your code looked a bit illogical — I modified the example to use the variables given.

Try this instead:

var industry = 'testing';
var i = assets_results.length - 1;
for (; i > 0; i--) {

    var asset = assets_results[i],
        asset_industry = asset['industry'];
    if (industry != asset_industry) { assets_results.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