javascript - 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
}
}
解决方案
filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
将结果分配给您的变量
neighbors = neighbors.filter(neighbor => !neighbor.isVisited);
推荐阅读
- cocoapods - 我正在尝试将我的 owm 豆荚添加到 cocoapods 但在终端中它给了我这个错误
- javascript - 如何从节点中的发布请求返回对前端的响应?
- html - 如何正确操作 div 以创建带有分支的树?
- xml - XSL 文件不会创建表。我究竟做错了什么。XSL 和支持的 XML 都在下面。请帮忙。第一次使用代码
- java - 如何使用优先队列根据键值对的值进行排序
- python - 输入数字时如何显示包含数字的列表
- typescript - discord.js / typescript / heroku / github:语法错误:无法在模块外使用导入语句
- arrays - C:Hashtable的索引数组,它本身由N个“结构节点”组成:努力访问单个元素
- python - 表格视图不可编辑
- python - Netmiko read_channel() 和 Clear_buffer() 不打印输出