2

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

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

每一个看起来都是这样的...

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

我正在遍历数组,搜索每个 Array.id 以查看它是否与第二个数组中的任何 id 匹配...

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

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

但是,此代码仅适用于拼接 self.collection 数组中的三个对象,然后它会中断并给出以下错误:

Uncaught TypeError: Cannot read property 'id' of undefined 

导致错误的行是这一行...

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

谁能告诉我我在这里做错了什么?

4

2 回答 2

6

因为收集的长度会改变,所以诀窍是从后到前循环

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);
    };
}
于 2013-08-15T20:04:18.840 回答
1

迭代数组时不应更改数组的长度。

您正在尝试做的是过滤,并且有一个特定的功能。例如:

[1,2,3,4,5,6,7,8,9,10].filter(function(x){ return (x&1) == 0; })

将只返回偶数。

在您的情况下,解决方案可能只是:

self.collection = self.collection.filter(function(k){
    return fbContactIDs.indexOf(k.id) > -1;
});

或者,如果其他人保留了对的引用self.collection并且您需要对其进行原地变异:

self.collection.splice(0, self.collection.length,
                       self.collection.filter(function(k){
    return fbContactIDs.indexOf(k.id) > -1;
}));

如果由于某种原因您喜欢一次处理一个元素而不是使用元素,filter并且您需要就地执行此操作,那么一种简单的方法是读写方法:

var wp = 0; // Write ptr
for (var rp=0; rp<L.length; rp++) {
    if (... i want to keep L[x] ...) {
        L[wp++] = L[rp];
    }
}
L.splice(wp);

一次从数组中删除一个元素是一项O(n**2)操作(因为对于您删除的每个元素,以下所有元素都必须向下滑动一个位置),而读写方法是O(n).

于 2013-08-15T20:04:48.950 回答