[英]Initialize a two-dimensional array in JavaScript
我想创建一个二维数组,用布尔值初始化,设置为false。 目前我正在使用这种数组创建方法:
const rows = 3
const cols = 5
const nestedArray = new Array(rows).fill(
new Array(cols).fill(false)
)
nestedArray
看起来很好,但是一旦我改变了nestedArray[0][2]
的值, nestedArray[1][2]
和nestedArray[2][2]
也会改变。
我想这是因为子数组是相同的,可能是因为它们通过引用而不是通过值填充到父数组中。
相反,创建一组不相同的子阵列的优雅而有效的方法是什么?
您可以使用嵌套的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);
您可以使用Array.from
方法创建行,其中第二个参数是map
方法, 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)
另一种方法是在行数组上使用扩展语法...
然后您可以在该数组上使用map
方法。
const rows = 3 const cols = 5 const nestedArray = [...Array(rows)].map(_ => Array(cols).fill(false)) nestedArray[0][1] = true; console.log(nestedArray)
const nestedArray = Array(rows).fill(false).map(x => Array(cols).fill(false))
试试这个
也许是这样的:
const rows = 3 const cols = 5 const nestedArray = new Array(rows).fill(0); nestedArray.forEach((e, i, a) => a[i] = new Array(cols).fill(false)); console.log(nestedArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.