具有非顺序索引数组的 .splice() 数组 - javascript
我有一个像这样的数组
Array['one','two','three','four','five']
,并且有一个像这样的数组,
Array['2','4','0']
指示我希望删除的第一个数组或 .splice()
中元素的索引,因此结果数组将如下所示
Array['two','four'] // <--- note no undefined positions
如果您尝试并循环遍历索引并为每个索引进行拼接,在第一次拼接之后,索引会根据被删除的元素而更改。
我怎样才能做到这一点?
I have an array like this
Array['one','two','three','four','five']
and I have an array like this
Array['2','4','0']
indicating the indexes of the elements in the first array I wish to remove or .splice()
so the resulting array would look like this
Array['two','four'] // <--- note no undefined positions
If you try and loop through the indexes and just do a splice for each one, after the first splice your indexes change according to the element that was removed.
How can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以开始以相反的顺序拼接数组中的索引。即从数组的长度循环到0。
首先拼接索引4,然后拼接索引2。
编辑:正如您提到的,索引数组不需要按相同的顺序,您可以按升序对索引数组进行排序,然后实现上述逻辑。
You can start splicing the indexes from the array in reverse order. i.e. Loop from the length of array to 0.
First splice index 4 and then index 2.
EDIT: As you mentioned the indexes array need not be in same order, you can sort the indexes array in ascending order and then implement the above logic.