是否有从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' ]
其他回答
非破坏性拆卸:
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;
}
你可以使用underscore.js。这真的让事情变得简单。
例如,用这个:
var result = _.without(['three','seven','eleven'], 'seven');
结果是[' 3 ',' 11 ']。
在你的情况下,你必须写的代码是:
ary = _.without(ary, 'seven')
它减少了你编写的代码。
我尝试使用上面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元素之外的所有元素。
最简单的解决方案是:
array—用于删除某些元素的数组valueForRemove; valueForRemove—用于删除的元素;
array.filter(arrayItem => !array.includes(valueForRemove));
更简单:
array.filter(arrayItem => arrayItem !== valueForRemove);
不漂亮,但有用:
array.filter(arrayItem => array.indexOf(arrayItem) != array.indexOf(valueForRemove))
不漂亮,但有用:
while(array.indexOf(valueForRemove) !== -1) {
array.splice(array.indexOf(valueForRemove), 1)
}
附注:filter()方法创建一个包含所有通过所提供函数实现的测试的元素的新数组。参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
你要的是滤镜
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
这将允许你做以下事情:
var ary = ['three', 'seven', 'eleven'];
var aryWithoutSeven = ary.filter(function(value) { return value != 'seven' });
console.log(aryWithoutSeven); // returns ['three', 'eleven']
这一点在其他地方也有注意到:https://stackoverflow.com/a/20827100/293492