1

I have a javascript code as below.

var row = new Array(7);
row.fill(0);
var state = new Array(7);
state.fill(row);
state[0][3] = 2;
console.log(state);

My issue is, when I change one element state[0][3] = 2; it affects all rows. All rows 3rd index value becomes 2. Can someone tell what is wrong in this code?

Vineesh
  • 3,762
  • 20
  • 37
  • this line `state.fill(row);` will **apply** `row` array to each `state` item - by **reference** – RomanPerekhrest Oct 06 '17 at 09:08
  • Does this answer your question? [Array.prototype.fill() with object passes reference and not new instance](https://stackoverflow.com/questions/35578478/array-prototype-fill-with-object-passes-reference-and-not-new-instance) – Heretic Monkey Apr 14 '21 at 19:13

1 Answers1

4

Can someone tell what is wrong in this code?

You're using one row array for all your entries in state. fill takes the value you give it and puts that value in the target array repeatedly. The value you're giving it is a reference to the single array you've created, so all of those entries end up referring to the same row, like this:

                                          +−−−−−−−−−+
row−−−−−−−−−−−−−−−−−−−−−−−+−+−+−+−+−+−+−−>| (array) |
          +−−−−−−−−−+     | | | | | | |   +−−−−−−−−−+
state−−−−>| (array) |     | | | | | | |   | 0: 0    |
          +−−−−−−−−−+     | | | | | | |   | 1: 0    |
          | 0       |−−−−−+ | | | | | |   | 2: 0    |
          | 1       |−−−−−−−+ | | | | |   | 3: 0    |
          | 2       |−−−−−−−−−+ | | | |   | 4: 0    |
          | 3       |−−−−−−−−−−−+ | | |   | 5: 0    |
          | 4       |−−−−−−−−−−−−−+ | |   | 6: 0    |
          | 5       |−−−−−−−−−−−−−−−+ |   +−−−−−−−−−+
          | 6       |−−−−−−−−−−−−−−−−−+
          +−−−−−−−−−+

You'll need to create a new row array for each slot in state:

let state = Array.from({length:7}, () => {
  return new Array(7).fill(0);
});
state[0][3] = 2;
console.log(state);
.as-console-wrapper {
  max-height: 100% !important;
}

...or with only features present in ES5:

var state = [0,0,0,0,0,0,0].map(function() {
  return [0,0,0,0,0,0,0];
});
state[0][3] = 2;
console.log(state);
.as-console-wrapper {
  max-height: 100% !important;
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875