JavaScript Array: Remove Elements Based on Condition in forEach Loop
To delete elements from an array in JavaScript, you can use the 'splice()' method. In order to delete the elements in the 'forEach' loop, you'll need to keep track of the indices of the elements you want to remove and then remove them after the loop has finished. Here's an example:
const indicesToRemove = [];
arr.forEach((point, index) => {
if (point.x >= this.rect.attrs.x &&
point.x <= (this.rect.attrs.x + this.rect.attrs.width) &&
point.y >= this.rect.attrs.y &&
point.y <= (this.rect.attrs.y + this.rect.attrs.height)) {
console.log(666333, point);
indicesToRemove.push(index);
}
});
indicesToRemove.forEach((index) => {
arr.splice(index, 1);
});
In this example, the 'indicesToRemove' array is used to store the indices of the elements that match the condition. After the loop, the 'splice()' method is called for each index in 'indicesToRemove' to remove the corresponding element from the 'arr' array.
原文地址: https://www.cveoy.top/t/topic/pcDh 著作权归作者所有。请勿转载和采集!