You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中Array.filter返回原数组,无法筛选未访问节点如何解决?

问题诱因
  • JavaScript内置的Array.filter()方法是纯函数,不会修改原数组,只会生成并返回一个符合筛选条件的新数组
  • 你当前的代码仅执行了过滤逻辑,但没有接收filter方法的返回值,原neighbors数组始终保留初始的所有邻接节点,所以前后打印结果完全一致
修复方案

直接将filter方法返回的新数组赋值给变量,或者直接返回该结果即可,修改后的代码参考如下:

export function getUnvisitedNeighbors(grid, node) {
    const { row, col } = node;
    const neighbors = [];
    if (row < grid.length - 1) neighbors.push(grid[row + 1][col]);
    if (col < grid[0].length - 1) neighbors.push(grid[row][col + 1]);
    if (row > 0) neighbors.push(grid[row - 1][col]);
    if (col > 0) neighbors.push(grid[row][col - 1]);
    console.log("before");
    console.log(neighbors);
    // 核心修改:接收filter返回的新数组
    const filteredNeighbors = neighbors.filter(neighbor => !neighbor.isVisited);
    console.log("after")
    console.log(filteredNeighbors);
    return filteredNeighbors;
}

如果不需要打印中间结果,也可以简写为直接返回过滤结果:

export function getUnvisitedNeighbors(grid, node) {
    const { row, col } = node;
    const neighbors = [];
    if (row < grid.length - 1) neighbors.push(grid[row + 1][col]);
    if (col < grid[0].length - 1) neighbors.push(grid[row][col + 1]);
    if (row > 0) neighbors.push(grid[row - 1][col]);
    if (col > 0) neighbors.push(grid[row][col - 1]);
    return neighbors.filter(neighbor => !neighbor.isVisited);
}

内容的提问来源于stack exchange,提问作者Sujio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 06:45:01