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

给定一个数组:

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

我想做的事情是:

removeItem('seven', ary);

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


当前回答

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

if(index!=-1){

   array.splice(index, 1);
}

其他回答

请不要使用带有delete的变体-它会在数组中留下一个洞,因为它不会在删除的项之后重新索引元素。

> Array.prototype.remove=function(v){
...     delete this[this.indexOf(v)]
... };
[Function]
> var myarray=["3","24","55","2"];
undefined
> myarray.remove("55");
undefined
> myarray
[ '3', '24', , '2' ]

你可以用以下两种方法:

const arr = ['1', '2', '3', '4'] // we wanna delete number "3"

第一种方式: arr.indexOf (3) ! = = 1 & & arr.splice (arr.indexOf (3), 1) 第二种方式(ES6)特别无突变: const newArr = arr。过滤(e => e !== '3')

CoffeeScript + jQuery变体:

arrayRemoveItemByValue = (arr,value) ->
  r=$.inArray(value, arr)
  unless r==-1
    arr.splice(r,1)
  # return
  arr

console.log arrayRemoveItemByValue(['2','1','3'],'3')

它只移除一个,而不是全部。

这样看看:

delete this.arrayName[this.arrayName.indexOf(value)];

参考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

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

希望这对你有所帮助