当你这样做时:
x = [["O", "O", "O"], ["O", "O", "O"], ["O", "O", "O"]];
Javascript 在内存中创建 3 个不同的数组,因此当您访问x[0][1]
您正在访问该数组。
当您使用:
x = new Array(3).fill(new Array(3).fill('O'))
您基本上用相同的数组填充数组 3 次,所以当您访问x[0][1]
您正在访问内存中的同一个数组,该数组也连接到x[1]
and x[2]
.
正如@Shidersz 所评论的,一个可能的迭代解决方案是:
// one liner:
Array.from({length: 3}, x => new Array(3).fill("0"));
这是创建一个数组并用从输入函数返回的值填充它。这是一个细分:
// 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")
});
文档在这里以供更多参考。