I'm trying to declare a "fixed" array of arrays for performance reasons, similar to an n*n matrix, as:
let n=5;
let cellTemplate="abc";
let array=new Array(n).fill(new Array(n).fill(cellTemplate));
knowing that no cell is going to exceed the memory of cellTemplate
. I know JavaScript only has fixed arrays for numbers, but I'm trying to eliminate possibility of it ever needing to re-copy the array in-case it exceeds its allocated memory.
It will look like this:
["abc","abc","abc","abc","abc"],
["abc","abc","abc","abc","abc"],
["abc","abc","abc","abc","abc"],
["abc","abc","abc","abc","abc"],
["abc","abc","abc","abc","abc"]
However, when I try to change its values with array[0][1]="xxx"
, instead of getting:
["abc","xxx","abc","abc","abc"],
["abc","abc","abc","abc","abc"],
["abc","abc","abc","abc","abc"],
["abc","abc","abc","abc","abc"],
["abc","abc","abc","abc","abc"]
I am getting:
["abc","xxx","abc","abc","abc"],
["abc","xxx","abc","abc","abc"],
["abc","xxx","abc","abc","abc"],
["abc","xxx","abc","abc","abc"],
["abc","xxx","abc","abc","abc"]
array[0].push("xxx")
would do something similar.
This behavior doesn't happen with normal JavaScript arrays declared with let array=[]
, which work correctly.
Why is it behaving like this & how do I fix it?
EDIT: Figured it out. Passing an object into the Array.prototype.fill() method passes a reference, causing aliasing behavior instead of a new array in every row.