简体   繁体   中英

I can't remove this specific items from this array

I know it's very simple, but tried searching and could'nt find anything that would solve my problem.

So let's say I have this array:

 var chicken = [10, 45, 150, 5000, 25000, 100000, 150000];

and I want to remove everything except 25000. So I tried a simple iteration:

 for (var w=0; w<chicken.length; w++){
     if (chicken[w]<25000 || chicken[w]>25000){
    chicken.splice(w,1);
     }
 }

And it doesn't work. The output is [ 45, 5000, 25000, 150000 ], don't know why.

The reason it doesn't work is because your array length is changing as you splice each item. If you want to loop and remove, use a reverse loop:

for (var i = chicken.length - 1; i >= 0; i--) {
    if (chicken[i] !== 25000) chicken.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