在fill()返回错误的矩阵后,在矩阵中设置值

wha*_*123 4 javascript

如果我像这样初始化矩阵

x = [["O", "O", "O"], ["O", "O", "O"], ["O", "O", "O"]];
Run Code Online (Sandbox Code Playgroud)

然后设置 x[0][1] = "X" 它返回

[ [ 'O', 'X', 'O' ], [ 'O', 'O', 'O' ], [ 'O', 'O', 'O' ] ]
Run Code Online (Sandbox Code Playgroud)

符合预期

但是,如果我将矩阵初始化如下:

x = new Array(3).fill(new Array(3).fill('O'))
Run Code Online (Sandbox Code Playgroud)

然后 x[0][1] = "X" 它还给我

[ [ 'O', 'X', 'O' ], [ 'O', 'X', 'O' ], [ 'O', 'X', 'O' ] ]
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?

avi*_*per 7

执行此操作时:

x = [["O", "O", "O"], ["O", "O", "O"], ["O", "O", "O"]];
Run Code Online (Sandbox Code Playgroud)

Javascript在内存中创建了3个不同的数组,因此当您访问时,您x[0][1]仅在访问该数组。

使用时:

x = new Array(3).fill(new Array(3).fill('O'))
Run Code Online (Sandbox Code Playgroud)

您基本上是用相同的数组填充该数组3次,因此访问时,x[0][1]您正在访问的内存中也连接到x[1]和的同一数组x[2]

正如@Shidersz所评论的那样,可能的迭代解决方案是:

// one liner:
Array.from({length: 3}, x => new Array(3).fill("0"));
Run Code Online (Sandbox Code Playgroud)

这将创建一个数组,并使用输入函数返回的值填充该数组。这是一个细分:

// same as previous only longer with comments
// Create an Array from the first argument,
//as modified by the mapping function in the 2nd argument
Array.from(
  // This could be any array like object. 
  // In the case of length it just reads the length property
  // and iterates that number of times,
  // so it could be useful if you want to 
  // fill the top array with 100000 arrays.
  {length: 3},
  // x argument for the mapping is irrelevant
  x => {
    // returning the array with 3 "0" strings in it.
    return  new Array(3).fill("0")
  });

Run Code Online (Sandbox Code Playgroud)

此处文档可获取更多参考。