首页 > 解决方案 > javascript数组过滤器返回相同的数组

问题描述

我有一个节点的邻居数组,我试图根据节点属性 isVisited 进行过滤。目前它返回相同的数组,我希望它只返回一个!isVisited 的数组。

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);
    neighbors.filter(neighbor => !neighbor.isVisited);     //returning same array
    console.log("after")
    console.log(neighbors);
    return neighbors;
}

控制台日志: 在此处输入图像描述

我是如何创建节点的:


function createNode(row, col) {
    return {
        isVisited: false,
        row: row,
        col: col,
        startnode: row === START_NODE_ROW && col === START_NODE_COL,
        endnode: row === END_NODE_ROW && col === END_NODE_COL,
        distance: Infinity,
        isWall: false,
        previousNode: null
    }
}

标签: javascriptarrays

解决方案


filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

将结果分配给您的变量

neighbors = neighbors.filter(neighbor => !neighbor.isVisited);

推荐阅读