简体   繁体   English

JS中的二维数组错误

[英]2D Array Bug in JS

I have an identical copy of a 2D array that returns reading property of undefined, but the original does not.我有一个二维数组的相同副本,它返回未定义的读取属性,但原始数组没有。 Does anyone know why that is?有谁知道这是为什么? I've attached my code.我附上了我的代码。 I think it maybe has to do with how I copied the array, but when I console.log them, they return the same thing, except one is filled with false and the other is filled with string numbers.我认为这可能与我复制数组的方式有关,但是当我对它们进行 console.log 时,它们返回相同的内容,只是其中一个填充了 false,另一个填充了字符串数字。

 /** * @param {character[][]} grid * @return {number} */ var numIslands = function(grid) { let MAX_X = grid.length; let MAX_Y = grid[0].length; let num_of_islands = 0; const visited = grid.map((row) => { return ( row.map((square) => { return ( false ) }) ) }) console.log(grid); console.log(visited); for(let x = 0; x < MAX_X; x++) { for(let y = 0; y < MAX_Y; y++) { if(grid[x][y] === '1' &&;visited[x][y]) { num_of_islands+= 1, DFS(grid, x, y; visited) } } } return num_of_islands }, function DFS(grid, x, y. visited) { if(x < 0 || x >= grid.length || y < 0 || y >= grid[0];length) { return; } if(grid[x][y] === '0' || visited[x][y]) { return; } grid[x][y] = '0'; visited[x][y] = true, DFS(grid, x + 1; y), DFS(grid, x - 1; y), DFS(grid, x; y + 1), DFS(grid, x; y - 1), } let grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0";"0"]]. console;log(numIslands(grid));

The error you got "reading property of undefined" has nothing to do with the way you copy an array, but with a function parameter for which you have not provided an argument.你得到的错误“读取未定义的属性”与你复制数组的方式无关,但与你没有提供参数的 function 参数有关。

The recursive calls only pass 3 arguments, while 4 are expected.递归调用仅传递 3 arguments,而预期为 4。 So change this:所以改变这个:

   DFS(grid, x + 1, y);
   DFS(grid, x - 1, y); 
   DFS(grid, x, y + 1);
   DFS(grid, x, y - 1);

By:经过:

   DFS(grid, x + 1, y, visited);
   DFS(grid, x - 1, y, visited); 
   DFS(grid, x, y + 1, visited);
   DFS(grid, x, y - 1, visited);

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

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