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

给定一个数组:

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

我想做的事情是:

removeItem('seven', ary);

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


当前回答

方法1

var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf('seven'); // get index if value found otherwise -1

if (index > -1) { //if found
  ary.splice(index, 1);
}

方法2

一条衬垫

var ary = ['three', 'seven', 'eleven'];
filteredArr = ary.filter(function(v) { return v !== 'seven' })


// Or using ECMA6:
filteredArr = ary.filter(v => v !== 'seven')

其他回答

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')

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

一行代码就可以了,

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

// Remove item 'seven' from array
var filteredArray = arr.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]

// In ECMA6 (arrow function syntax):
var filteredArray = arr.filter(e => e !== 'seven')

这就使用了JS中的filter函数。它在IE9及更高版本中得到支持。

它的功能(来自文档链接)

Filter()为数组中的每个元素调用一次所提供的回调函数,并构造一个包含所有回调返回强制为true的值的新数组。回调只对数组中已赋值的索引调用;对于已删除或从未赋值的索引,不调用该方法。未通过回调测试的数组元素将被跳过,并且不包含在新数组中。

基本上,这和所有其他for (var key in ary){…}解决方案,除了从IE6开始支持for in构造。

基本上,filter是一个方便的方法,与for in构造(AFAIK)相比,它看起来更好(并且是可链的)。

我使用了投票最多的选项,并创建了一个函数,该函数将使用另一个不需要的单词数组清理一个单词数组:

function cleanArrayOfSpecificTerms(array,unwantedTermsArray) {
  $.each(unwantedTermsArray, function( index, value ) {
    var index = array.indexOf(value);
    if (index > -1) {
      array.splice(index, 1);        
    }
  });
  return array;
}

要使用,请执行以下操作:

var notInclude = ['Not','No','First','Last','Prior','Next', 'dogs','cats'];
var splitTerms = ["call", "log", "dogs", "cats", "topic", "change", "pricing"];

cleanArrayOfSpecificTerms(splitTerms,notInclude)

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

希望这对你有所帮助

最简单的解决方案是:

array—用于删除某些元素的数组valueForRemove; valueForRemove—用于删除的元素;

array.filter(arrayItem => !array.includes(valueForRemove));

更简单:

array.filter(arrayItem => arrayItem !== valueForRemove);

不漂亮,但有用:

array.filter(arrayItem => array.indexOf(arrayItem) != array.indexOf(valueForRemove))

不漂亮,但有用:

while(array.indexOf(valueForRemove) !== -1) {
  array.splice(array.indexOf(valueForRemove), 1)
}

附注:filter()方法创建一个包含所有通过所提供函数实现的测试的元素的新数组。参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter