是否有从JavaScript数组中删除项的方法?

给定一个数组:

var ary = ['three', 'seven', 'eleven'];

我想做的事情是:

removeItem('seven', ary);

我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。


当前回答

一个非常干净的解决方案工作在所有浏览器,没有任何框架是分配一个新的数组,并简单地返回它没有你想删除的项:

/**
 * @param {Array} array the original array with all items
 * @param {any} item the time you want to remove
 * @returns {Array} a new Array without the item
 */
var removeItemFromArray = function(array, item){
  /* assign a empty array */
  var tmp = [];
  /* loop over all array items */
  for(var index in array){
    if(array[index] !== item){
      /* push to temporary array if not like item */
      tmp.push(array[index]);
    }
  }
  /* return the temporary array */
  return tmp;
}

其他回答

var index = array.indexOf('item');

if(index!=-1){

   array.splice(index, 1);
}

从数组中删除所有匹配的元素(而不仅仅是第一个,这似乎是这里最常见的答案):

while ($.inArray(item, array) > -1) {
    array.splice( $.inArray(item, array), 1 );
}

我使用jQuery来完成这些繁重的工作,但是如果您想要本地化,您就可以理解了。

ES6路。

const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);

一个非常干净的解决方案工作在所有浏览器,没有任何框架是分配一个新的数组,并简单地返回它没有你想删除的项:

/**
 * @param {Array} array the original array with all items
 * @param {any} item the time you want to remove
 * @returns {Array} a new Array without the item
 */
var removeItemFromArray = function(array, item){
  /* assign a empty array */
  var tmp = [];
  /* loop over all array items */
  for(var index in array){
    if(array[index] !== item){
      /* push to temporary array if not like item */
      tmp.push(array[index]);
    }
  }
  /* return the temporary array */
  return tmp;
}

indexOf是一个选项,但它的实现基本上是在整个数组中搜索值,因此执行时间随着数组大小的增加而增加。(所以我猜每个浏览器都是这样,我只检查了Firefox)。

我没有IE6可以检查,但我敢打赌,你可以在几乎任何客户端机器上以这种方式每秒检查至少一百万个数组项。如果[数组大小]*[每秒搜索次数]可能超过一百万,您应该考虑不同的实现。

基本上你可以使用一个对象为你的数组创建一个索引,如下所示:

var index={'three':0, 'seven':1, 'eleven':2};

任何正常的JavaScript环境都会为这些对象创建一个可搜索的索引,这样无论对象有多少属性,您都可以快速地将键转换为值。

这只是基本的方法,根据你的需要,你可以组合几个对象和/或数组,使相同的数据快速搜索不同的属性。如果您指定了确切的需求,我可以建议更具体的数据结构。