这部分负责处理 val 数组中的数据,因此 i 一切都是整数并将其保存在输出数组中。(val 数组有时包含浮点数,我无法使用它们)
假设下一个被处理的元素有 ax 和 y 对,它们已经在输出数组中,并且带有任何其他颜色。如何用新对象替换旧对象。
val.forEach(element => {
output.push({
x: Math.round(element.x / element.width),
y: Math.round(element.y / element.height),
color: mapColorToBlock(element.color)
})
});
/* val array...
[
{"x":0,"y":0,"color":"blue","width":256,"height":256},
{"x":0,"y":256,"color":"blue","width":256,"height":256},
{"x":256,"y":256,"color":"blue","width":256,"height":256},
{"x":256,"y":0,"color":"blue","width":256,"height":256},
{"x":0,"y":256,"color":"lime","width":256,"height":256}
]
*/
/*output array after the processing(notice how there are 2 objects with x = 0 and y = 1 (the second and last entry in output))
[
{ x: 0, y: 0, color: 12 },
{ x: 0, y: 1, color: 12 },
{ x: 1, y: 1, color: 12 },
{ x: 1, y: 0, color: 12 },
{ x: 0, y: 1, color: 6 }
]
*/
新对象替换旧对象很重要。(新条目不必与旧对象在数组中的位置相同)在这种情况下,输出数组将如下所示。
[
{ x: 0, y: 0, color: 12 },
{ x: 1, y: 1, color: 12 },
{ x: 1, y: 0, color: 12 },
{ x: 0, y: 1, color: 6 }
]
Shuvo 答案的修改版本。
只有当 mapColorToBlock 可以在对传递的相同值的连续调用中返回不同的结果时,这个才有意义,否则 Shuvo 跳过重复项的答案会更好。
“重要的是,新对象替换旧对象”...
let val = [
{"x":0,"y":0,"color":"blue","width":256,"height":256},
{"x":0,"y":256,"color":"blue","width":256,"height":256},
{"x":256,"y":256,"color":"blue","width":256,"height":256},
{"x":256,"y":0,"color":"blue","width":256,"height":256},
{"x":0,"y":256,"color":"lime","width":256,"height":256}
];
let output = [];
val.forEach(element => {
const x = Math.round(element.x / element.width);
const y = Math.round(element.y / element.height);
const found = output.find(item => item.x === x && item.y === y);
if (found) {
found.color = mapColorToBlock(element.color);
} else {
output.push({
x: x,
y: y,
color: mapColorToBlock(element.color)
})
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句