如何通过在Javascript中循环从数组中删除多个项目 [英] How to remove multiple items from an array via looping in Javascript

查看:91
本文介绍了如何通过在Javascript中循环从数组中删除多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个包含多个值的javascript数组:

  var keymap = {'name':'foobaz', 
'mappings':[{'id':1,'key':'b'},
{'id':2,'key':'c'},
{ 'id':3,'key':'d'},
{'id':1,'key':'e'},
{'id':10,'key': 'f'},
{'id':7,'key':'g'},
{'id':1,'key':'h'}]
}

我想删除密钥为'b'的所有条目。请注意,ID对应于后端ID。我想要做的是删除一些映射(例如,所有'id'为'1')。



我尝试的是:<对于(var i = 0; i< keymap ['mappings']。length; i ++){
if (keymap ['mappings'] [i] ['id'] === id_to_match){
keyboard_map ['mappings']。splice(i,1);
}
}

但是,slice会改变数组的索引-place,因此现在 i 将不会指向正确的索引点(因为任何更高的索引现在将 in 其中 n 将是之前完成的切片数。



实现此方法的正确方法是什么? / p>

解决方案

一种简单的方法是减少迭代器(这是因为你每次迭代都读取了长度 - 所以请确保你避免缓存长度)

  for(var i = 0; i< keymap ['mappings']。length; i ++){
if(keymap ['mappings'] [i] ['id'] === id_to_match){
keyboard_map ['mappings']。splice(i,1);
i--;
}
}


So, I have a javascript array of multiple values:

var keymap = {'name': 'foobaz', 
              'mappings': [{'id': 1, 'key': 'b'},
                          {'id': 2, 'key': 'c'},
                          {'id': 3, 'key': 'd'},
                          {'id': 1, 'key': 'e'},
                          {'id': 10, 'key': 'f'},
                          {'id': 7, 'key': 'g'},
                          {'id': 1, 'key': 'h'}]
}

I want to remove any entries where key is 'b'. Note the ids correspond to the backend ids. What I want to do is to remove some of the mappings (for example, all with 'id' as '1').

What I've tried is:

for (var i = 0; i < keymap['mappings'].length; i++) {
    if (keymap['mappings'][i]['id'] === id_to_match) {
        keyboard_map['mappings'].splice(i, 1);
    }
}

However, slice will change the indexes of the array in-place, and therefore now i won't point to the correct index point (as any indexes higher will now be i-n where n would be the number of slices done before.

What is the correct way to implement this?

解决方案

An easy way is to decrement the iterator (this works since you read the length every iteration - so make sure you avoid caching the length)

for (var i = 0; i < keymap['mappings'].length; i++) {
 if (keymap['mappings'][i]['id'] === id_to_match) {
    keyboard_map['mappings'].splice(i, 1);
    i--;
 }
}

这篇关于如何通过在Javascript中循环从数组中删除多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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