是否有从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' ]
其他回答
另一个变化:
if (!Array.prototype.removeArr) {
Array.prototype.removeArr = function(arr) {
if(!Array.isArray(arr)) arr=[arr];//let's be nice to people who put a non-array value here.. that could be me!
var that = this;
if(arr.length){
var i=0;
while(i<that.length){
if(arr.indexOf(that[i])>-1){
that.splice(i,1);
}else i++;
}
}
return that;
}
}
它又是循环中的indexOf(),但前提是要删除的数组相对于要清理的数组较小;每次移除都会缩短while循环。
var remove = function(array, value) {
var index = null;
while ((index = array.indexOf(value)) !== -1)
array.splice(index, 1);
return array;
};
你可以使用underscore.js。这真的让事情变得简单。
例如,用这个:
var result = _.without(['three','seven','eleven'], 'seven');
结果是[' 3 ',' 11 ']。
在你的情况下,你必须写的代码是:
ary = _.without(ary, 'seven')
它减少了你编写的代码。
indexOf是一个选项,但它的实现基本上是在整个数组中搜索值,因此执行时间随着数组大小的增加而增加。(所以我猜每个浏览器都是这样,我只检查了Firefox)。
我没有IE6可以检查,但我敢打赌,你可以在几乎任何客户端机器上以这种方式每秒检查至少一百万个数组项。如果[数组大小]*[每秒搜索次数]可能超过一百万,您应该考虑不同的实现。
基本上你可以使用一个对象为你的数组创建一个索引,如下所示:
var index={'three':0, 'seven':1, 'eleven':2};
任何正常的JavaScript环境都会为这些对象创建一个可搜索的索引,这样无论对象有多少属性,您都可以快速地将键转换为值。
这只是基本的方法,根据你的需要,你可以组合几个对象和/或数组,使相同的数据快速搜索不同的属性。如果您指定了确切的需求,我可以建议更具体的数据结构。
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')
它只移除一个,而不是全部。