如何在 JavaScript 中遍历数组并删除元素 [英] How to iterate over an array and remove elements in JavaScript

查看:34
本文介绍了如何在 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 中遍历数组并删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆