繁体   English   中英

javascript数组过滤器返回相同的数组

[英]javascript array filter returning same array

我有一个节点的邻居数组,我试图根据节点属性 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
    }
}

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

将结果分配给您的变量

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

我看到有几个人告诉过你眼前的问题。 您还可以考虑更改逻辑,以便您只需从与节点的距离为 1 和 isVisited 的网格数组进行映射。 距离为 1 的唯一方法是如果它们高于、低于、向右或向左 1 增量(对角线将是 sqrt(2))。 你可以把它写成一行,虽然我可能会写一个距离公式。 您可以删除几行并避免检查您的数字是否在范围内。

 const node = {row: 4, col: 10}; //const {row, col} = node; const grid = [ {isVisited: true, row: 3, col: 9 }, {isVisited: false, row: 3, col: 10}, {isVisited: true, row: 4, col: 9 }, {isVisited: false, row: 4, col: 11}, {isVisited: true, row: 5, col: 10}, {isVisited: true, row: 5, col: 11} ]; const dist=(n,r,c)=>{return Math.abs(Math.sqrt(Math.pow(n.row-r, 2)+Math.pow(n.col-c, 2)))} let neighbors = grid.filter( function(e) {return e.isVisited && dist(e, this.row, this.col) == 1; }, node); console.log(neighbors);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM