简体   繁体   中英

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]

Why is it like that? I just want the first item in the first array to be set as 1

Because you use 1 instance of an array to fill you first array (arr). So arr[0] and arr[1] are actually the same instance, they point to the same address. If you want to fill you array arr with new arrays, loop over you first array arr, and then assign them new array.

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 .

But all the copies of Array(2) are the deep-copies.

So, changes in one of the deep-copy will be reflected in all the copies of 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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