简体   繁体   中英

How to delete array value by splice?

Stuck in delete array value by splice .Tried with delete and splice doesn't work..

var arr = [];
 arr[2] = 22;
 arr[5] = 3;
 arr[99] = 3343;
 for(var i in arr){
    if(i != 2){
    arr.splice(i,1);
    }
   //delete arr[i];
 }
 console.log(arr);// [2: 22, 98: 3343]
 //wanted [2:22]

I want to delete all except index 2 ,It is only delete one.

No need of a for loop in the splice, you may use: arr.splice(0,arr.length)

But if you want to just delete all elements just do arr=[] .

Alternative method would be to loop & pop :

while(arr.length > 0) {
    arr.pop();
}

In the case you might need to get a sequential item by item deletion starting from the the middle of an array you should iterate in reverse in order not to get the shifting indexes get in front of you.

 var arr = new Array(10).fill("").map((e,i) => e = "item:" +i), i = 7; console.log(JSON.stringify(arr)); while (i>2) console.log(JSON.stringify(arr.splice(i--,1))); // splice item at index i and decrease i by one console.log(JSON.stringify(arr));

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