问题描述
我有一个元素数组,需要从中删除某些元素.问题是 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 中遍历数组并删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)