简体   繁体   English

Javascript 二维数组 - 用值初始化的最佳方式

[英]Javascript 2D array - best way to initialize with values

I'm trying to create a 2D array visited to show where the code has already visited in the grid .我正在尝试创建一个二维数组visited以显示代码在grid中已经访问过的位置。 The way I have it now is that each row in visited is a shallow copy.我现在的方式是visited的每一行都是一个浅拷贝。 Changing the value in one row, changes in all of the rows.更改一行中的值,将更改所有行。 What's the best way to initialize the starting values in visited in this case?在这种情况下,初始化visited中的起始值的最佳方法是什么?

let grid = 
  [
    ["0", "1", "0"],
    ["1", "0", "1"],
    ["0", "1", "0"],
  ]

let visited = new Array(grid.length).fill(new Array(grid[0].length).fill(false))

visited[0][1]= true

console.log(visited);

Output: Output:

[
  [ false, true, false ],
  [ false, true, false ],
  [ false, true, false ]
]

You can use map to create new array for each row您可以使用 map 为每一行创建新数组

 let grid = [ ["0", "1", "0"], ["1", "0", "1"], ["0", "1", "0"], ] let visited = Array.from({length: grid.length}, () => Array(grid[0].length).fill(false)) visited[0][1]= true console.log(visited);

Also you can replace new Array() with Array.from您也可以用Array.from替换new Array()

ie Array.from({length: grid.length}, () => Array(grid[0].length).fill(false))Array.from({length: grid.length}, () => Array(grid[0].length).fill(false))

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

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