在JavaScript中初始化二维数组

lys*_*igk 4 javascript arrays

我想创建一个二维数组,用布尔值初始化,设置为false.目前我正在使用这种数组创建方法:

const rows = 3
const cols = 5

const nestedArray = new Array(rows).fill(
    new Array(cols).fill(false)
)
Run Code Online (Sandbox Code Playgroud)

nestedArray看起来不错,但只要我改变的值nestedArray[0][2],值nestedArray[1][2],并nestedArray[2][2]也得到改变.

我想这是因为子数组是相同的,可能是因为它们通过引用而不是通过值填充到父数组中.

相反,创建一组不相同的子阵列的优雅而有效的方法是什么?

Ori*_*ori 6

您可以使用嵌套Array.from()调用:

const rows = 3
const cols = 5

const nestedArray = Array.from({ length: rows }, () => 
  Array.from({ length: cols }, () => false)
);
  
nestedArray[0][1] = 'value'; // example of changing a single cell
  
console.log(nestedArray);
Run Code Online (Sandbox Code Playgroud)


Nen*_*car 5

您可以使用Array.frommethod 来创建第二个参数为mapmethod 的行以及Array.fill列。

const rows = 3
const cols = 5

const nestedArray = Array.from(Array(rows), _ => Array(cols).fill(false));
nestedArray[0][1] = true;
console.log(nestedArray)
Run Code Online (Sandbox Code Playgroud)

另一种方法是...在行数组上使用扩展语法,这样您就可以map在该数组上使用方法。

const rows = 3
const cols = 5

const nestedArray = [...Array(rows)].map(_ => Array(cols).fill(false))
nestedArray[0][1] = true;
console.log(nestedArray)
Run Code Online (Sandbox Code Playgroud)