如何在多维数组中分配单个元素(JavaScript)

时间:2022-11-13 00:04:44

I don't know why I'm seeing the below:

我不知道为什么我会看到以下内容:

const sideLength = 4;
const multiArray = new Array(sideLength).fill(new Array(sideLength));
console.log(multiArray)
var counter = 1;
multiArray[3][1] = counter;
console.log('multiArray:', multiArray)

Console output:

控制台输出:

[ [ , , ,  ], [ , , ,  ], [ , , ,  ], [ , , ,  ] ]
multiArray: [ [ , 1, ,  ], [ , 1, ,  ], [ , 1, ,  ], [ , 1, ,  ] ]

I would have expected the second line of output to be:

我原以为第二行输出是:

multiArray: [ [ , , ,  ], [ , , ,  ], [ , , ,  ], [ , 1, ,  ] ]

Why is that 1 being added to every array's index=1 element?

为什么将1添加到每个数组的index = 1元素中?

2 个解决方案

#1


6  

The fill() method fills all the elements of an array from a start index to an end index with a static value.

fill()方法使用静态值将数组的所有元素从起始索引填充到结束索引。

That means all elements would refer to the same array. Changing the value of of one element would change the value of all elements since they refer to the same static object

这意味着所有元素都将引用相同的数组。更改一个元素的值将改变所有元素的值,因为它们引用相同的静态对象

#2


2  

You can use Array.from() to create an Array having a specific .length

您可以使用Array.from()创建具有特定.length的Array

const sideLength = 4;
const multiArray = Array.from({length:sideLength}, () => new Array(sideLength));
console.log(multiArray)
var counter = 1;
multiArray[3][1] = counter;
console.log('multiArray:', multiArray)

#1


6  

The fill() method fills all the elements of an array from a start index to an end index with a static value.

fill()方法使用静态值将数组的所有元素从起始索引填充到结束索引。

That means all elements would refer to the same array. Changing the value of of one element would change the value of all elements since they refer to the same static object

这意味着所有元素都将引用相同的数组。更改一个元素的值将改变所有元素的值,因为它们引用相同的静态对象

#2


2  

You can use Array.from() to create an Array having a specific .length

您可以使用Array.from()创建具有特定.length的Array

const sideLength = 4;
const multiArray = Array.from({length:sideLength}, () => new Array(sideLength));
console.log(multiArray)
var counter = 1;
multiArray[3][1] = counter;
console.log('multiArray:', multiArray)