Javascript:如何从数组中清除未定义的值 [英] Javascript: How to clear undefined values from an array

查看:117
本文介绍了Javascript:如何从数组中清除未定义的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历数组并删除并跳过元素,直到只有一个存在。我已经尝试过拼接,但它会弄乱我的循环,因为来自arr [1]的元素会变成arr [0]等。

I'm trying to loop through an array and delete and skip the elements until only one is existing. i've tried splicing but it messes up my loop because the element from arr[1] then becomes arr[0] etc.

假设有10个人。我想删除1号人员然后保留2号人员然后移除3号人员并保留4号人员。此模式将一直持续到只剩下一人。

Let's say there are 10 people. I'd like to remove person 1 then keep person 2 then remove person 3 and keep person 4. This pattern will go on until only one is left.

任何类型的帮助都可以。

any kind of help will do.

推荐答案

你不应该这样做在迭代过程中更改集合,不仅仅是JavaScript,而是所有语言,定义一个新数组并添加要删除的数组,稍后再迭代该数组以从第一个删除。

you should not change the collection during the iterating, not just JavaScript but all language, define a new array and add those ones you want to delete in it, and iterate that one later to delete from first one.

这篇关于Javascript:如何从数组中清除未定义的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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