JavaScript:如何遍历对象数组获取高程按n递减的对象序列?
问题分析与解决方案
原代码存在的核心问题
- 循环匹配逻辑错误:原代码将
startPointsForClosest[i]与topographyData[i]按索引一一对应比较,但实际需求是用结果数组最后一个元素的高程作为基准,在整个地形数据中寻找下一个符合条件的节点,而非索引绑定。 - 条件判断逻辑颠倒:原条件
startPointsForClosest[i]?.topography.elevation >= topographyData[i]?.topography.elevation - n无法筛选出高程递减n的节点,正确逻辑应为寻找高程不高于基准高程 - n的节点(即基准高程 - 节点高程 >= n)。 - 循环终止逻辑不合理:原循环仅遍历一次地形数据,无法持续迭代寻找后续符合条件的节点,导致只能得到少量结果。
修正后的代码
function MakeRoute(highestEl, n) { const startPointsForClosest = [highestEl]; let remainingData = [...topographyData]; while (true) { const lastElevation = startPointsForClosest.at(-1).topography.elevation; // 寻找下一个高程至少比当前最后一个节点低n的元素 const nextPoint = remainingData.find(item => lastElevation - item.topography.elevation >= n ); if (!nextPoint) break; startPointsForClosest.push(nextPoint); // 移除已选中的节点,避免重复选择 remainingData = remainingData.filter(item => item !== nextPoint); } return startPointsForClosest; } // 调用示例 MakeRoute({ "latlng": { "lat": 40.738800829681864, "lng": -73.7568126408477 }, "topography": { "elevation": 38.600000000000364, "slope": 1.3792065335718062, "aspect": 111.03751102530578, "resolution": 57.85092357410129 } }, 2);
代码说明
- 初始化:将初始最高节点存入结果数组,复制地形数据到
remainingData,避免修改原数据。 - 持续迭代寻找:通过
while循环不断查找下一个符合条件的节点:- 每次取结果数组最后一个节点的高程作为基准。
- 在剩余数据中筛选出高程至少比基准值低
n的节点。
- 终止循环:当没有符合条件的节点时,退出循环并返回结果数组。
- 去重处理:每次选中节点后,从剩余数据中移除该节点,防止重复添加。
优化:寻找最接近目标高程的节点
如果需要优先选择最接近基准高程 - n的节点(而非第一个符合条件的),可修改节点查找逻辑:
const nextPoint = remainingData .filter(item => lastElevation - item.topography.elevation >= n) .sort((a, b) => { const targetDiff = lastElevation - n; return Math.abs(a.topography.elevation - targetDiff) - Math.abs(b.topography.elevation - targetDiff); })[0];
内容的提问来源于stack exchange,提问作者Antonio Pavicevac-Ortiz
相关产品推荐
相关产品推荐

