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

给定一个数组:

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

我想做的事情是:

removeItem('seven', ary);

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


当前回答

你可以使用underscore.js。这真的让事情变得简单。

例如,用这个:

var result = _.without(['three','seven','eleven'], 'seven');

结果是[' 3 ',' 11 ']。

在你的情况下,你必须写的代码是:

ary = _.without(ary, 'seven')

它减少了你编写的代码。

其他回答

你可以用以下两种方法:

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

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

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现在是[红的,黑的,白的]

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

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

ES6路。

const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);

非破坏性拆卸:

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;
}