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

给定一个数组:

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

我想做的事情是:

removeItem('seven', ary);

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


当前回答

非破坏性拆卸:

function removeArrayValue(array, value)
{
    var thisArray = array.slice(0); // copy the array so method is non-destructive

    var idx = thisArray.indexOf(value); // initialise idx

    while(idx != -1)
    {
        thisArray.splice(idx, 1); // chop out element at idx

        idx = thisArray.indexOf(value); // look for next ocurrence of 'value'
    }

    return thisArray;
}

其他回答

我尝试使用上面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元素之外的所有元素。

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

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

    return array;
};

这样看看:

for(var i in array){
    if(array[i]=='seven'){
        array.splice(i,1);
        break;
    }
}

在函数中:

function removeItem(array, item){
    for(var i in array){
        if(array[i]==item){
            array.splice(i,1);
            break;
        }
    }
}

removeItem(array, 'seven');

你可以使用Lodash _来实现这一点。删除功能。

Var array = [' 3 ', ' 7 ', ' 11 ']; Var even = _。删除(数组,函数(e) { 返回e !== 'seven'; }); console.log(均等的); <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script> .js

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