ac3*_*360 2 javascript arrays jquery json backbone.js
我有几百个JSON对象的数组......
var self.collection = [Object, Object, Object, Object, Object, Object…]
Run Code Online (Sandbox Code Playgroud)
每个看起来像这样......
0: Object
id: "25093712"
name: "John Haberstich"
Run Code Online (Sandbox Code Playgroud)
我正在遍历数组搜索每个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);
};
});
Run Code Online (Sandbox Code Playgroud)
但是,此代码仅用于从self.collection数组中拼接三个对象,然后它会断开并给出以下错误:
Uncaught TypeError: Cannot read property 'id' of undefined
Run Code Online (Sandbox Code Playgroud)
导致错误的行是这一行......
if (fbContactIDs.indexOf(k.id) > -1) {
Run Code Online (Sandbox Code Playgroud)
有人能告诉我这里有什么问题吗?
因为收集的长度会发生变化,所以诀窍就是从后向前循环
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);
};
}
Run Code Online (Sandbox Code Playgroud)