gpt4 book ai didi

javascript - 从 Javascript 数组中删除多个对象中途中断

转载 作者:行者123 更新时间:2023-12-01 02:30:43 25 4
gpt4 key购买 nike

我有一个包含数百个 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) {

谁能告诉我我错了什么?

最佳答案

因为集合的长度会改变,所以技巧是从后到前循环

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 - 从 Javascript 数组中删除多个对象中途中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18260784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com