从数组中查找并删除元素
Find and remove element from array
如果我有一个javascript数字数组
[1, 2, 5, 7, 5, 4, 7, 9, 2, 4, 1]
我想搜索该数组并删除一个特定的数字,例如 4 给我
[1, 2, 5, 7, 5, 7, 9, 2, 1]
最好的方法是什么
我在想它可能看起来像
for(var i = 0; i < myarray.length; i++) {
if(myarray[i] == 4) {
myarray.remove(i)
}
}
但是数组没有remove
函数。 此外,如果我从数组中删除一个元素,除非我更正它,否则它会弄乱我的i
。
您可以使用
.splice()
从数组中删除一个或多个项目,如果您从数组的后到前进行迭代,则在删除项目时索引不会混乱。
var arr = [1, 2, 5, 7, 5, 4, 7, 9, 2, 4, 1];
for (var i = arr.length - 1; i >= 0; i--) {
if (arr[i] == 4) {
arr.splice(i, 1);
}
}
就个人而言,我喜欢在过滤器方法中使用可重用的函数:
//generic filter:
function without(a){return this!=a;}
//your data:
var r= [1, 2, 5, 7, 5, 4, 7, 9, 2, 4, 1];
//your data filtered against 4:
var no4=r.filter(without, 4);
//verify no 4s:
alert(no4); //shows: "1,2,5,7,5,7,9,2,1"
如果你想改变原始数组,你可以简单地擦除新值并将其推送到旧数组中:
function without(a){return this!=a;}
var r= [1, 2, 5, 7, 5, 4, 7, 9, 2, 4, 1], //orig
r2=r.slice(); //copy
r.length=0; //wipe orig
[].push.apply( r, r2.filter(without, 4)); //populate orig with filtered copy
r; // == [1, 2, 5, 7, 5, 7, 9, 2, 1]
jQuery的创建者John Resig创建了一个非常方便的Array.move方法,我总是在项目中使用它。
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
因此,您可以像这样使用代码:
// Remove the second item from the array
myarray.remove(1);
// Remove the second-to-last item from the array
myarray.remove(-2);
// Remove the second and third items from the array
myarray.remove(1,2);
// Remove the last and second-to-last items from the array
myarray.remove(-2,-1);
---编辑----
for(var i = 0; i < myarray.length; i++) {
if(myarray[i] == 4) {
myarray.remove(i);
}
}
像这样使用代码来删除特定值。
这是一个基于索引的删除函数
function remove(array, index){
for (var i = index; i < arr.length-1; i++) {
array[i] = array[i+1];
}
}
基本上,这样做是将所有元素从索引移动到"左"。不太确定拼接是如何工作的,但我猜它的工作方式完全相同。
将该函数添加到代码后,您所要做的就是。
for(var i = 0; i < myarray.length; i++) {
if(myarray[i] == 4) {
remove(myarray,i);
}
}
我更喜欢做这样的事情:
removeEmail(event){
myarray.splice(myarray.indexOf(event.target.id), 1)
}
myaraay.splice() 要删除,myarray.indexOf() 给出数字或任何你想要从数组内部删除的内容。这是最简单的方法,无需循环。:)
相关文章:
- 从组件状态的数组中删除元素
- 从数组中删除元素的最佳方法是:javascript/jquery
- 正则表达式条件来删除元素
- 使用javascript删除元素时出现的问题
- 当会话存储阵列中存在大量元素时,如何从中删除元素
- 从角度数组中删除元素
- AngularJs localStorage在循环中删除元素
- 在使用jquery插入之前删除元素
- 如何删除元素列表中的类并添加到另一个元素 Jquery.
- 更新分组条形图(转换或删除元素组)
- 向下滚动后如何用同一类逐个删除元素
- 如何防止 jQuery 事件在删除元素时冒泡
- 从jQuery对象中删除元素
- 如何删除元素的结束标记,添加一些文本,然后重新添加标记
- 从画布中删除元素
- 如何解析html以删除元素并只返回其位置的标题
- 使用 V8 从密集数组中删除元素的最佳方法是什么
- 如何使用jquery删除元素
- 根据成员属性从数组中删除元素
- 从中删除元素'的父元素,并将其附加到其他元素