Why do these two javascript 2d-arrays behave differently? -


in function, have defined 2 arrays, first (array1), has pre-initialized length. added second array (array2) testing because thought first behaving strangely.

my code:

function test(n = 3) {    array1 = new array(n).fill(new array(n));    array2 = [      [undefined, undefined, undefined],      [undefined, undefined, undefined],      [undefined, undefined, undefined]    ];      document.getelementbyid("output").innerhtml = json.stringify(array1) + " (array 1) <br/>" + json.stringify(array2) + " (array 2)<br/><br/><hr/>";        (i = 0; < n; i++) {      array1[i][0] = i;      array2[i][0] = i;    }      document.getelementbyid("output").innerhtml += json.stringify(array1) + " (array 1) <br/>" + json.stringify(array2) + " (array 2)<br/><br/><hr/>";    }
<button onclick="test();">press test</button>    <br/><br/>  <div id="output"></div>

in for loop, try change first value of second dimensions. should output [[0, undefined, undefined], [1, undefined, undefined], [2, undefined, undefined]], second array does.

my questions are: why happen? and, how can make pre-initialized array length n in both dimensions, behaves second array?

because array.fill

the fill() method fills elements of array start index end index static value.

takes static value , fills array it. therefore in every element of array1 same array of filling.

function test(n = 3) {      var array1 = new array(n).fill(new array(n)),          array2 = [[undefined, undefined, undefined], [undefined, undefined, undefined], [undefined, undefined, undefined]],          i;        (i = 0; < n; i++) {          array1[i][0] = i;          array2[i][0] = i;      }        document.getelementbyid("output").innerhtml = array1 + " (array 1) <br/>" + array2 + " (array 2)<br/><br/><i>the commas nothing in between mean undefined.</i>";      console.log(array1);      console.log(array2);  }
<button onclick="test();">press test</button><br/><br/>  <div id="output"></div>

to independent filled array, use array.from , map new array mapped values.

var array = array.from({ length: 3 }, _ => array.from({ length: 3 }, _ => 4));    array[0][0] = 0;  console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -