1👍
✅
Iterating over an array by i
as index, when you’re potentially changing the array as you’re iterating, is definitely going to give you bugs
What about something like this?:
var RandomClass = {
// this is how i update
Youtube: [],
UpdateYT: function () {
// console.log('Youtube => ', this.Youtube)
this.Youtube = this.Youtube.filter(yt => !yt.deleted);
},
addCardYT: function (num) {
this.Youtube.push({deleted: false, num:num})
},
}
RandomClass.addCardYT(1);
RandomClass.addCardYT(2);
console.log(RandomClass.Youtube);
RandomClass.Youtube[0].deleted = true;
RandomClass.UpdateYT();
console.log(RandomClass.Youtube);
[edit]
If you insisted on wanting to iterate over i
and delete them as they come up, what you should do is start at the end of the array and work your way backwards.
👤TKoL
0👍
const youtube = [
{ id: 1, deleted: false },
{ id: 2, deleted: true },
{ id: 3, deleted: false },
{ id: 4, deleted: true },
{ id: 5, deleted: true },
{ id: 6, deleted: false },
];
console.log('Initial', youtube);
const update = () => {
let i = youtube.length - 1
while (i != 0) {
if (youtube[i].deleted) youtube.splice(i, 1);
i--;
}
}
update();
console.log('Updated', youtube);
Edit: TKoL was right; iterating over an array like that can create bugs if two consecutive elements need to be removed. Iterating over it backwards should work just fine.
Source:stackexchange.com