答案 0 :(得分:1)
在这种情况下,我通常使用两个循环:
const results = [];
for(const dx of [-1, 0, 1]) {
for(const dy of [-1, 0, 1]) {
if(dx === 0 && dy === 0) continue;
results.push({ x: x + dx, y: y + dy });
}
}
或者只是:
const neighbours = [
[-1, -1], [-1, 0], [-1, 1],
[ 0, -1], /*0, 0*/ [ 0, 1],
[ 1, -1], [ 1, 0], [ 1, 1]
];
const results = neighbours.map(([dx, dy]) => ({ x: x + dx, y: y + dy }));
答案 1 :(得分:1)
您不仅要实现这一目标,而且要很好地实现它是一件好事!在我个人看来,可以通过使用以下内容中明确的“邻接”定义来使之“好”。代码。
// This code makes "adjacency" explicit by working with "adjacency offset generators"
// These are functions which return all offsets that move a point to all of its adjacent points
let manhattanAdjacencyOffsets = dist => {
// Returns adjacency offsets corresponding to all points within a manhattan distance of `dist`
let ret = [];
for (let x = -dist; x <= dist; x++) { for (let y = -dist; y <= dist; y++) {
if (x === 0 && y === 0) continue; // Don't include the 0,0 point
ret.push({ x, y });
}}
return ret;
};
// Now `nCoordinates` becomes very short:
let nCoordinates = (x0, y0, adjacencyOffsets) => {
return adjacencyOffsets.map(({ x, y }) => ({ x: x + x0, y: y + y0 }));
};
// Here's manhattan adjacency offsets with a distance of 1
let adjacencyOffsets = manhattanAdjacencyOffsets(1);
// And here's all neighbours of the point (10,20), with regard to those offsets
let neighbours = nCoordinates(10, 20, adjacencyOffsets);
console.log(neighbours);
我喜欢这种方法,因为它使“邻接”变得明确。您甚至可以定义新的邻接函数来更改代码对“邻接”的定义。
例如,您可以使用笛卡尔距离而不是曼哈顿距离(源图块的圆形范围内的所有点):
let cartesianAdjacencyOffsets = dist => {
let sqrDist = dist * dist;
let ret = [];
let min = Math.ceil(-dist);
let max = Math.floor(dist);
for (let x = min; x <= max; x++) { for (let y = min; y <= max; y++) {
if (x === 0 && y === 0) continue; // Don't include the 0,0 point
if (sqrDist < x * x + y * y) continue; // Don't include points too far away
ret.push({ x, y });
}}
return ret;
};