How to iterate over an array and remove elements in JavaScript(如何在 JavaScript 中遍历数组并删除元素)
问题描述
我有一个元素数组,需要从中删除某些元素.问题是 JavaScript 似乎没有 for each 循环,如果我使用 for 循环,我会遇到问题,它基本上试图检查数组边界之外的元素,或者由于索引更改而丢失数组中的元素.让我告诉你我的意思:
I have an array of elements and need to remove certain ones from it. The problem is that JavaScript doesn't seem to have a for each loop and if I use a for loop I run into problems with it basically trying to check elements beyond the bounds of the array, or missing elements in the array because the indexes change. Let me show you what I mean:
var elements = [1, 5, 5, 3, 5, 2, 4];
for(var i = 0; i < elements.length; i++){
if(elements[i] == 5){
elements.splice(i, 1);
}
}
问题是当元素[1]被移除时,元素[2]变成了元素[1].所以第一个问题是某些元素从未被检查过.另一个问题是 .length 发生变化,如果我对边界进行硬编码,那么我可能会尝试检查超出数组边界的元素.那么,完成这个极其简单的事情的最佳方法是什么?
The problem is that when elements[1] is removed, elements[2] becomes elements[1]. So first problem is that some elements are never examined. The other problem is that .length changes and if I hard code the bounds, then I might be trying to examine elements beyond the bounds of the array. So what's the best way to do this incredibly simple thing?
推荐答案
从头开始!
var elements = [1, 5, 5, 3, 5, 2, 4];
for(var i = elements.length -1; i >= 0 ; i--){
if(elements[i] == 5){
elements.splice(i, 1);
}
}
这篇关于如何在 JavaScript 中遍历数组并删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 JavaScript 中遍历数组并删除元素
基础教程推荐
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 动态更新多个选择框 2022-01-01