简体   繁体   English

如何在javascript中重置二维数组中的值

[英]how to reset value in a 2D array in javascript

I am really confused about this 2D array.我真的对这个二维数组感到困惑。

For example:例如:

let arr = Array(2)
arr.fill(Array(2))

arr[0][0]=1

And the result of arr is [1,empty][1,empty]arr的结果是[1,empty][1,empty]

Why is it like that?为什么会这样? I just want the first item in the first array to be set as 1我只想将第一个数组中的第一项设置为 1

Because you use 1 instance of an array to fill you first array (arr).因为您使用数组的 1 个实例来填充第一个数组 (arr)。 So arr[0] and arr[1] are actually the same instance, they point to the same address.所以 arr[0] 和 arr[1] 实际上是同一个实例,它们指向同一个地址。 If you want to fill you array arr with new arrays, loop over you first array arr, and then assign them new array.如果您想用新数组填充数组 arr,请循环遍历您的第一个数组 arr,然后为它们分配新数组。

const arr = Array(2);

for (let i = 0; i < arr.length; i++) {
    arr[i] = Array(2);
}

arr[0][0] = 1;

Array(2) is the empty array that is copied to each element of arr . Array(2)是复制到arr 的每个元素的空数组。

But all the copies of Array(2) are the deep-copies.但是Array(2) 的所有副本都是深层副本。

So, changes in one of the deep-copy will be reflected in all the copies of Array(2) .因此,深层副本之一的更改将反映在Array(2) 的所有副本中。

 let arr = Array(2) arr.fill(Array(2)) arr[0][0]= 1 // [ [ 1, <1 empty item> ], [ 1, <1 empty item> ] ] arr[0][1] = 2 // [ [ 1, 2 ], [ 1, 2 ] ]

The docu says...文档说...

Value to fill the array with.用于填充数组的值。 (Note all elements in the array will be this exact value.) (注意数组中的所有元素都将是这个确切的值。)

That means they share the same adress in memory.这意味着它们在内存中共享相同的地址。

You need a different approach to fill your array..您需要一种不同的方法来填充数组。

 let arr = Array.from({length: 2}, e => Array(2)) arr[0][0]=1 console.log(arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM