>》>》>》>》

数组删除元素

一、length

JavaScript中Array的length属性非常有特点一一它不是只读的。因此,通过设置这个属性可以从数组的末尾移除项或添加新项

1 var colors = ["red", "blue", "grey"];   //创建一个包含3个字符串的数组
2 colors.length = 2;
3 console.log(colors[2]);  //undefined

二、delete关键字

1 var arr = [1, 2, 3, 4];
2 delete arr[0];
3 
4 console.log(arr);   //[undefined, 2, 3, 4]

可以看出来,delete删除之后数组长度不变,只是被删除元素被置为undefined了。

 

三、pop

1 var colors = ["red", "blue", "grey"];
2 var item = colors.pop();
3 console.log(item);      //"grey"
4 console.log(colors.length);    //2

可以看出,在调用Pop方法时,数组返回最后一项,即”grey”,数组的元素也仅剩两项。

 

四、shift方法,它能够移除数组中的第一个项并返回该项,并且数组的长度减1。

1 var colors = ["red", "blue", "grey"];
2 var item = colors.shift();
3 console.log(item);      //"red"
4 console.log(colors.length);    //2

 

五、splice操作方法 

在删除数组元素的时候,它可以删除任意数量的项,只需要指定2个参数:要删除的第一项的位置和要删除的项数,例如splice(0, 2)会删除数组中的前两项。

1 var colors = ["red", "blue", "grey"];
2 var item = colors.splice(0, 1);
3 console.log(item);      //"red"
4 console.log(colors);    //["blue", "grey"]

 

六、filter方法:

找出元素不是”red”的项数返回给colors(其实是得到了一个新的数组),从而达到删除的作用。

1 var colors = ["red", "blue", "grey"];
2 
3 colors = colors.filter(function(item) {
4     return item != "red"
5 });
6 
7 console.log(colors);    //["blue", "grey"]

 

七、ForEach循环来对比元素找到之后将其删除:

1  var colors = ["red", "blue", "grey"];
2 
3 colors.forEach(function(item, index, arr) {
4     if(item == "red") {
5        arr.splice(index, 1);
6     }
7 });

所谓的迭代方法就是用循环迭代数组元素发现符合要删除的项则删除,用的最多的地方可能是数组中的元素为对象的时候,根据对象的属性例如ID等等来删除数组元素

 

八、在原型上添加方法删除:

 1 Array.prototype.remove = function(dx) {
 2 
 3     if(isNaN(dx) || dx > this.length){
 4         return false;
 5     }
 6 
 7     for(var i = 0,n = 0;i < this.length; i++) {
 8         if(this[i] != this[dx]) {
 9             this[n++] = this[i];
10         }
11     }
12     this.length -= 1;
13 };
14 
15 var colors = ["red", "blue", "grey"];
16 colors.remove(1);
  console.log(colors); //["red", "grey"]

 

posted @ 2019-09-20 09:46  大、锤  阅读(881)  评论(0编辑  收藏  举报