是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
是否有从JavaScript数组中删除项的方法?
给定一个数组:
var ary = ['three', 'seven', 'eleven'];
我想做的事情是:
removeItem('seven', ary);
我已经查看了splice(),但它只删除了位置号,而我需要一些东西来删除其值的项目。
当前回答
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]
其他回答
indexOf是一个选项,但它的实现基本上是在整个数组中搜索值,因此执行时间随着数组大小的增加而增加。(所以我猜每个浏览器都是这样,我只检查了Firefox)。
我没有IE6可以检查,但我敢打赌,你可以在几乎任何客户端机器上以这种方式每秒检查至少一百万个数组项。如果[数组大小]*[每秒搜索次数]可能超过一百万,您应该考虑不同的实现。
基本上你可以使用一个对象为你的数组创建一个索引,如下所示:
var index={'three':0, 'seven':1, 'eleven':2};
任何正常的JavaScript环境都会为这些对象创建一个可搜索的索引,这样无论对象有多少属性,您都可以快速地将键转换为值。
这只是基本的方法,根据你的需要,你可以组合几个对象和/或数组,使相同的数据快速搜索不同的属性。如果您指定了确切的需求,我可以建议更具体的数据结构。
在全局函数中,我们不能直接传递自定义值,但有很多方法,如下所示
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
在所有唯一的值中,您可以:
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]
另一个变化:
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循环。
//编辑感谢MarcoCI的建议
试试这个:
function wantDelete(item, arr){
for (var i=0;i<arr.length;i++){
if (arr[i]==item){
arr.splice(i,1); //this delete from the "i" index in the array to the "1" length
break;
}
}
}
var goodGuys=wantDelete('bush', ['obama', 'bush', 'clinton']); //['obama', 'clinton']
希望这对你有所帮助