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

给定一个数组:

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

我想做的事情是:

removeItem('seven', ary);

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


当前回答

//编辑感谢MarcoCI的建议

试试这个:

function wantDelete(item, arr){
  for (var i=0;i<arr.length;i++){
    if (arr[i]==item){
      arr.splice(i,1); //this delete from the "i" index in the array to the "1" length
      break;
    }
  }  
}
var goodGuys=wantDelete('bush', ['obama', 'bush', 'clinton']); //['obama', 'clinton']

希望这对你有所帮助

其他回答

当你需要移除一个在数组中多次出现的值时(例如。[1,2,2,2,4,5,6])。

function removeFrmArr(array, element) {
  return array.filter(e => e !== element);
};
var exampleArray = [1,2,3,4,5];
removeFrmArr(exampleArray, 3);
// return value like this
//[1, 2, 4, 5]

可以使用splice从数组中删除单个元素,但splice不能从数组中删除多个相似的元素。

function singleArrayRemove(array, value){
  var index = array.indexOf(value);
  if (index > -1) array.splice(index, 1);
  return array;
}
var exampleArray = [1,2,3,4,5,5];
singleArrayRemove(exampleArray, 5);
// return value like this
//[1, 2, 3, 4, 5]

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

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

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

在全局函数中,我们不能直接传递自定义值,但有很多方法,如下所示

 var ary = ['three', 'seven', 'eleven'];
 var index = ary.indexOf(item);//item: the value which you want to remove

 //Method 1
 ary.splice(index,1);

 //Method 2
 delete ary[index]; //in this method the deleted element will be undefined

你可以使用without或pull from Lodash:

const _ = require('lodash');
_.without([1, 2, 3, 2], 2); // -> [1, 3]
var index = array.indexOf('item');

if(index!=-1){

   array.splice(index, 1);
}