JavaScript 数组遍历删除元素并更新界面:如何移除矩形内像素点?
您想在 JavaScript 中删除矩形区域内的像素点,但发现使用 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) arr.splice(index, 1) } }) 删除后,界面仍然显示所有点。这是因为在遍历数组过程中删除元素会导致索引发生变化,可能引发问题。
为了解决这个问题,建议创建一个新的数组,将符合条件的点添加到新数组中,然后更新界面上的显示。以下是修改后的代码:
let newPoints = []; // 创建一个新的数组用于存储符合条件的点
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);
// 将符合条件的点添加到新数组中
newPoints.push(point);
}
});
// 更新界面上的显示
arr = newPoints;
通过将 arr 数组重新赋值为新的数组 newPoints,可以避免在遍历过程中删除元素导致的索引变化问题。
更新界面上的显示的具体方法取决于您使用的界面库或框架。您可以根据新的 arr 数组来更新界面中显示矩形点的部分,或者使用其他方法清除之前显示的所有矩形点,然后重新绘制新的 arr 数组中的点。
请根据您的具体应用场景和界面库的文档来选择适合的方法来更新界面上的显示。
原文地址: https://www.cveoy.top/t/topic/pcGf 著作权归作者所有。请勿转载和采集!