0

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.

Silver
  • 21
  • 3
  • `Array.from({length:n},e => Array(n).fill(cellTemplate))` – cmgchess May 16 '23 at 16:24
  • 1
    Please don't put tags in the title. There's a Tags box for putting the tags in and the most popular tag is automatically added to the `` of the HTML document for SEO. – Heretic Monkey May 16 '23 at 16:30
  • you pass a variable by reference not by value, read about reference vs value in js. if you do the same by passing the whole arrays array and change the one you said you'll see the behavior as expected – Raphael Ben Hamo May 16 '23 at 16:44
  • 1
    @RaphaelBenHamo "you pass a variable by reference" - No. https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language – Unmitigated May 16 '23 at 16:45

0 Answers0