简体   繁体   English

如何通过拼接删除数组值?

[英]How to delete array value by splice?

Stuck in delete array value by splice .Tried with delete and splice doesn't work..splice卡在删除数组值中。尝试删除和拼接不起作用..

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.我想删除除索引2之外的所有内容,只删除一个。

No need of a for loop in the splice, you may use: arr.splice(0,arr.length)拼接中不需要 for 循环,可以使用: arr.splice(0,arr.length)

But if you want to just delete all elements just do arr=[] .但是,如果您只想删除所有元素,只需执行arr=[]

Alternative method would be to loop & pop :另一种方法是循环和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));

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

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