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

给定一个数组:

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

我想做的事情是:

removeItem('seven', ary);

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


当前回答

var remove = function(array, value) {
    var index = null;

    while ((index = array.indexOf(value)) !== -1)
        array.splice(index, 1);

    return array;
};

其他回答

你可以使用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);
}
var index = array.indexOf('item');

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)

我尝试使用上面jbaron中的函数方法,但发现我需要保持原始数组完整以供以后使用,并创建一个像这样的新数组:

var newArray = referenceArray;

显然是通过引用而不是值创建的,因为当我从newArray中删除一个元素时,referenceArray也删除了它。所以我决定每次创建一个新数组,就像这样:

function newArrRemoveItem(array, item, newArray){
    for(var i = 0; i < array.length; i++) {
        if(array[i]!=item){
            newArray.push(array[i]);
        }
    }
}

然后我在另一个函数中这样使用它:

var vesselID = record.get('VesselID');
var otherVessels = new Array();
newArrRemoveItem(vesselArr,vesselID,otherVessels);

现在,vesselArr保持完整,而每次我执行上述代码时,othervessel数组都包含了除最新的vesselID元素之外的所有元素。