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

给定一个数组:

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

我想做的事情是:

removeItem('seven', ary);

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


当前回答

你可以使用lodash的拉函数

Var ary = [' 3 ', ' 7 ', ' 11 ']; _。拉(氩,' 7 ');// [' 3 ', ' 11 '] console.log(必要) < script src = " https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.6.1/lodash.js " > < /脚本>

其他回答

下面是一个使用jQuery的inArray函数的版本:

var index = $.inArray(item, array);
if (index != -1) {
    array.splice(index, 1);
}

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

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)

在所有唯一的值中,您可以:

a = new Set([1,2,3,4,5]) // a = Set(5) {1, 2, 3, 4, 5}
a.delete(3) // a = Set(5) {1, 2, 4, 5} 
[...a] // [1, 2, 4, 5]

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

希望这对你有所帮助

诀窍是从头到尾遍历数组,这样在删除元素时就不会弄乱下标。

var deleteMe = function( arr, me ){
   var i = arr.length;
   while( i-- ) if(arr[i] === me ) arr.splice(i,1);
}

var arr = ["orange","red","black", "orange", "white" , "orange" ];

deleteMe( arr , "orange");

Arr现在是[红的,黑的,白的]