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

查看:110
本文介绍了如何迭代数组并删除JavaScript中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列元素,需要从中删除某些元素。问题是JavaScript似乎没有为每个循环而且如果我使用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天全站免登陆