javascript - 获取周边坐标

标签 javascript arrays object ecmascript-6 coordinates

我有像这样的 x,y 坐标仪表板:

enter image description here

现在假设我在 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}, ...]

enter image description here

(现在我看到图像上的 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)

但这远非解决方案。那么完成这项任务的最佳方法是什么?

最佳答案

您需要遍历 xy值 - 并使用 <=达到你想要的范围:

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/

相关文章:

java - 处理类之间的对象

javascript - HTML Canvas 渐变仅显示一种颜色

javascript - v-for 之后的 Vue 指令

c# - 在 C# 的数组列表中查找数组的索引

javascript - 这些函数类型名称是什么?

json - 在 'parent'对象的.fromJson方法中从JSON提取对象

javascript - 代码的技术名称不属于任何功能

c# - 编辑评论框脚本为动态

c++ - 访问全局数组比作为参数传递更有效?

c - 在 C 中使用 "sscanf"函数解析字符串中的子字符串