JavaScript中数组元素删除的方法总结

  1. length
  2. delete
  3. 栈方法
  4. 队列方法
  5. 操作方法
  6. 迭代方法
  7. 原型方法

1.length

JavaScript中Array的length属性,通过设置这个属性可以从数组的末尾移除或添加新项。
var color = ["red","blue","grey"];

color.length = 2;

console.log(color[2]);        //undefined

2.delete

var arr = [1,2,3,4];

delete arr[0];

console.log(arr)         //[undefined,2,3,4]

注意:delete删除长度之后数组长度不变,只是被删除元素被置为undefined了。

3.栈方法

var colors = ["red",“blue”,"grey"];

var item = colors.pop();

console.log(item);    //“grey”
console.log(colors.length);  //2

在调用pop方法时,数组返回最后一项,即“grey”,数组的元素也只剩两项。

4.队列方法

队列数据结构的访问规则是FIFO(先进先出),队列在列表的末端添加项,从列表的前端移除项,使用shift方法,它能够移除数组中的第一个项并返回该项,并且数组的长度减1.

var colors = ["red","blue","grey"];

var item = colors.shift();

console.log(item);    //  "red"

console.log(colors.length);    //2

5.操作方法

splice()是最强大的数组方法,此处只介绍删除数组元素的方法。在数组元素的时候,可以删除任意数量的项,只需要指定2个参数:①要删除的第一项的位置,②要删除的项数。

例:splice(0,2)会删除数组中的前两项。

var colors = ["red","blue","grey"];

var item = colors.splice(0,1);

console.log(item);   //"red"
console.log(colors.length);  //["blue","grey"]

6.迭代方法

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

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

var colors = ["red","blue","grey"];

colors.forEach(function(item,index,arr){

  if(item == "red"){

    arr.splice(index,1);
  }

})

②  filter方法  (本人感觉最好用)

var colors = ["red","blue","grey"];

colors = colors.filter(function(item){

  return item != "red"

});

console.log(colors);  //  ["blue","grey"]

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

7.原型方法

通过在Array的原型上添加方法来达到删除的目的:

Array.prototype.remove = function(dx){

  if(isNaN(dx) || dx > this.length){

    return false;

  }

  for(var i = 0,n = 0;i < this.length;i++){

    if(this[i] != this[dx]){

      this[n++] = this[i];

    }

  }

  this.length -= 1;

}

var colors = ["red","blue","grey"];

colors.remove(1);

console.log(colors);  //  ["red","grey"]

在此把删除方法添加给了Array的原型对象,则在此环境中的所有Array对象都可以使用该方法。尽管可以这么做,但是我们不推荐在产品化的程序中来修改原生对象的原型。道理很简单,如果因某个实现中缺少某个方法,就在原生对象的原型中添加这个方法,那么当在另一个支持该方法的实现中运行代码时,就可能导致命名冲突。而且这样做可能会意外的导致重写原生方法。

原文地址:https://www.cnblogs.com/meiyanstar/p/13141803.html