优化JavaScript代码:使用矩形数据生成像素点数组
这段代码的功能是将矩形数据转换为像素点数组,并根据提供的擦除数据进行过滤。以下是优化后的代码:
comfirmEdit(obj) {
const newPixelData = [];
obj.newData.forEach(rect => {
const pixelData = this.getPointData1(rect);
newPixelData.push(...pixelData);
});
const deletePixelSet = new Set();
obj.delData.forEach(rect => {
const pixelData = this.getPointData(rect);
pixelData.forEach(pixel => {
const pixelKey = `${pixel.x},${pixel.y}`;
deletePixelSet.add(pixelKey);
});
});
this.imgCircle = this.imgCircle.filter(pixel => {
const pixelKey = `${Math.floor(pixel.x + this.imgRect.x)},${Math.floor(pixel.y + this.imgRect.y)}`;
return !deletePixelSet.has(pixelKey);
});
newPixelData = newPixelData.filter(pixel => {
const pixelKey = `${Math.floor(pixel.x + this.imgRect.x)},${Math.floor(pixel.y + this.imgRect.y)}`;
return !deletePixelSet.has(pixelKey);
});
this.imgCircle.push(...newPixelData);
},
// 获取矩形中每个像素点的坐标
getPointData(rect) {
const { x, y, width: W, height: H } = rect.attrs;
return Array.from({ length: W * H }, (_, index) => {
const i = x + Math.floor(index / H);
const j = y + (index % H);
return { x: i, y: j };
});
},
// 获取矩形中每个像素点的坐标
getPointData1(rect) {
const { x, y, width: W, height: H } = rect.attrs;
const pixelData = [];
for (let i = x; i < x + W; i++) {
for (let j = y; j < y + H; j++) {
pixelData.push({ x: i - this.imgRect.x, y: j - this.imgRect.y });
}
}
return pixelData;
},
- 使用 map 函数代替 for 循环:在 getPointData 函数中,使用 map 函数代替 for 循环来生成像素点坐标数组。
- 使用 forEach 代替 for 循环:在 comfirmEdit 函数中,使用 forEach 函数代替 for 循环来遍历数组。
- 使用解构赋值:在 getPointData1 函数中,使用解构赋值来简化代码。
通过以上优化,代码变得更简洁和易读,同时也提高了代码的性能和可维护性。
原文地址: https://www.cveoy.top/t/topic/pknH 著作权归作者所有。请勿转载和采集!