是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
请不要使用带有delete的变体-它会在数组中留下一个洞,因为它不会在删除的项之后重新索引元素。
> Array.prototype.remove=function(v){
... delete this[this.indexOf(v)]
... };
[Function]
> var myarray=["3","24","55","2"];
undefined
> myarray.remove("55");
undefined
> myarray
[ '3', '24', , '2' ]
其他回答
一行代码就可以了,
var arr = ['three', 'seven', 'eleven'];
// Remove item 'seven' from array
var filteredArray = arr.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]
// In ECMA6 (arrow function syntax):
var filteredArray = arr.filter(e => e !== 'seven')
这就使用了JS中的filter函数。它在IE9及更高版本中得到支持。
它的功能(来自文档链接)
Filter()为数组中的每个元素调用一次所提供的回调函数,并构造一个包含所有回调返回强制为true的值的新数组。回调只对数组中已赋值的索引调用;对于已删除或从未赋值的索引,不调用该方法。未通过回调测试的数组元素将被跳过,并且不包含在新数组中。
基本上,这和所有其他for (var key in ary){…}解决方案,除了从IE6开始支持for in构造。
基本上,filter是一个方便的方法,与for in构造(AFAIK)相比,它看起来更好(并且是可链的)。
ES6路。
const commentsWithoutDeletedArray = commentsArray.filter(comment => comment.Id !== commentId);
在全局函数中,我们不能直接传递自定义值,但有很多方法,如下所示
var ary = ['three', 'seven', 'eleven'];
var index = ary.indexOf(item);//item: the value which you want to remove
//Method 1
ary.splice(index,1);
//Method 2
delete ary[index]; //in this method the deleted element will be undefined
let arr = [5, 15, 25, 30, 35];
console.log(arr); //result [5, 15, 25, 30, 35]
let index = arr.indexOf(30);
if (index > -1) {
arr.splice(index, 1);
}
console.log(arr); //result [5, 15, 25, 35]
你可以使用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