从JavaScript数组中删除多个对象打破中途 [英] Removing Multiple Objects from Javascript Array Breaks Half Way Through

查看:127
本文介绍了从JavaScript数组中删除多个对象打破中途的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几百JSON对象的数组...

I have an Array of a few hundred JSON Objects...

var self.collection = [Object, Object, Object, Object, Object, Object…]

每个人看起来像这样...

Each one looks like this...

0: Object
   id: "25093712"
   name: "John Haberstich"

我通过遍历数组搜索每个Array.id,看它是否在第二阵列相匹配的IDS ...

I'm iterating through the Array searching each Array.id to see if it matches any ids in a second Array...

   var fbContactIDs = ["1072980313", "2502342", "2509374", "2524864", "2531941"] 

   $.each(self.collection, function(index, k) {
        if (fbContactIDs.indexOf(k.id) > -1) {
            self.collection.splice(index, 1);
        };
    });

然而,这code只能拼接其中三个来自self.collection阵列的对象,然后它打破,并提供了以下错误:

However this code only works to splice three of the Objects from the self.collection array and then it breaks and gives the following error:

Uncaught TypeError: Cannot read property 'id' of undefined 

这是造成错误的行是这个...

The line that is causing the error is this one...

if (fbContactIDs.indexOf(k.id) > -1) {

谁能告诉我什么,我洞错在这里?

Could anyone tell me what I'm dong wrong here?

推荐答案

由于收集的长度会有所改变,唯一的办法就是从后循环前

Because the length of collection will change, the trick is to loop from rear to front

for (var index = self.collection.length - 1; index >= 0; index--) {
    k = self.collection[index];
    if (fbContactIDs.indexOf(k.id) > -1) {
        self.collection.splice(index, 1);
    };
}

这篇关于从JavaScript数组中删除多个对象打破中途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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