简体   繁体   中英

How to set one value in a two dimensional javascript array

I am trying to set a single value in a two dimensional array, but its not working.

Consider the following code taken from the many examples on the subject:

// create a 3x3 array with -1 in every position:
let a = new Array(3).fill(new Array(3).fill(-1))
console.log(`a: ${JSON.stringify(a)}`)
a[1][2] = 0
console.log(`a: ${JSON.stringify(a)}`)

The output is as follows:

a: [[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]]
a: [[-1,-1,0],[-1,-1,0],[-1,-1,0]]

As we can see, instead of setting a single cell, it as actually set 3 positions in the array to 0, ie it sets [0][2] and [1][2] and [2][2] = 0. Very odd.

I tried this:

let a = new Array(3).fill(new Array(3).fill(-1))
console.log(`a: ${JSON.stringify(a)}`)
a[1,2] = 0
console.log(`a: ${JSON.stringify(a)}`)

Which gives the even stranger result:

a: [[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]]
a: [[-1,-1,-1],[-1,-1,-1],0]

Am I going crazy, or does javascript not support setting a value in a 2 dimensional array?

First question:

That's because you fill the outer array with the same subarray! a[0] , a[1] and a[2] are all the same array! Because in JS objects (including arrays) are passed around using their references! What array.fill does is taking a parrameter (in this case a reference to an array) and assigns it to every item in the array. It's like this:

 var sub = new Array(3); sub.fill(-1); var a = []; a[0] = sub; a[1] = sub; a[2] = sub; a[0][1] = 0; console.log(sub); // changed too 

Because here is what array.fill is doing:

 var a = new Array(10); a.fill(Math.random()); console.log(a); // not 10 different random numbers, but the same random number is assigned to the whole array 

Second question:

It has nothing to do with arrays. It's a comma operator like the one used in the for loops (for example), to group expressions into one and returning the value of the last:

 console.log((1, 2)); // 2 console.log((1, 5, "last")); // last console.log((1, 5, 5 * 11 + 10)); // 65 // the parens are used to distinguish the comma operator from the parameter separator 

So a[1, 2] is the same as a[2] because the value of 1, 2 is 2 !

You are filling the array with same reference new Array(3).fill(-1) in all three rows and therefore any change to one will be reflected everywhere.

Try:

var a = new Array(n);
for (var i = 0; i < n; i++) {
  a[i] = new Array(n);
}
//where n = 3 for your case.

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