我有像这样的 x,y 坐标仪表板:
现在假设我在 4,4
上,我想获取包含 2 范围内 4,4 左右每个坐标的 x、y 的对象数组。
所以对象的输出数组应该是这样的
[{x: 2, y: 2}, {x: 3, y: 2}, {x: 4, y: 2}, {x: 5, y: 2}, {x: 6, y: 2}, ...]
(现在我看到图像上的 x,y 是相反的,对不起,错误)
我可以这样得到x:
const currentCoord = { x: 4, y: 4 };
const range = 2;
const coordsAround = [];
for(let i = 0; i < range * 2; i++) {
coordsAround.push({x: currentCoord.x - range + i, y: currentCoord.y})
}
console.log(coordsAround)
但这远非解决方案。那么完成这项任务的最佳方法是什么?
最佳答案
您需要遍历 x
和 y
值 - 并使用 <=
达到你想要的范围:
const currentCoord = { x: 4, y: 4 };
const range = 2;
const coordsAround = [];
for (let i = 0; i <= range * 2; i++) {
for (let j = 0; j <= range * 2; j++) {
coordsAround.push({ x: currentCoord.x - range + j, y: currentCoord.y - range + i });
}
}
console.log(coordsAround);
.as-console-wrapper { max-height: 100% !important; top: auto; }
关于javascript - 获取周边坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56732995/