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

给定一个数组:

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

我想做的事情是:

removeItem('seven', ary);

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


当前回答

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

 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

其他回答

//编辑感谢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']

希望这对你有所帮助

你要的是滤镜

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

这将允许你做以下事情:

var ary = ['three', 'seven', 'eleven'];
var aryWithoutSeven = ary.filter(function(value) { return value != 'seven' });
console.log(aryWithoutSeven); // returns ['three', 'eleven']

这一点在其他地方也有注意到:https://stackoverflow.com/a/20827100/293492

当你需要移除一个在数组中多次出现的值时(例如。[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]

鉴于没有一个漂亮的ES6函数,这里有一个简单且可重用的ES6函数。

const removeArrayItem = (arr, itemToRemove) => {
  return arr.filter(item => item !== itemToRemove)
}

用法:

const items = ['orange', 'purple', 'orange', 'brown', 'red', 'orange']
removeArrayItem(items, 'orange')

真的,我不明白为什么不能用

arr = arr.filter(value => value !== 'seven');

或者你可能想使用普通的JS

arr = arr.filter(function(value) { return value !== 'seven' });