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

给定一个数组:

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

我想做的事情是:

removeItem('seven', ary);

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


当前回答

你可以创建你自己的方法,传递数组和你想要删除的值:

function removeItem(arr, item){
 return arr.filter(f => f !== item)
}

然后你可以用:

ary = removeItem(ary, 'seven');

其他回答

ES6路。

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

鉴于没有一个漂亮的ES6函数,这里有一个简单且可重用的ES6函数。

const removeArrayItem = (arr, itemToRemove) => {
  return arr.filter(item => item !== itemToRemove)
}

用法:

const items = ['orange', 'purple', 'orange', 'brown', 'red', 'orange']
removeArrayItem(items, 'orange')

你可以像这样使用indexOf方法:

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

注意:对于IE8及以下版本,您需要对其进行填充

Var数组= [1,2,3,4] Var项= 3 var index = array.indexOf(item); 数组中。拼接(指数(1); console.log(数组)

你可以使用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 " > < /脚本>

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

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]