GeckStar GeckStar - 1 year ago 70
Javascript Question

new Array(_).fill(object) does not create new instances of object

ES6 allows us to fill an

with a certain value:

function emptyRow() {
return new Array(9).fill(0);

This function returns an
of length 9, filled with only zeros:

>> emptyRow()
<< Array [ 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

Now I want to generate an
that is filled with nine of those empty rows.

function emptyMatrix() {
return new Array(9).fill(emptyRow());

However, instead of
nine times, it seems to call it once and fills the new
with nine references to the object created by
. Naturally, if I change a value within any of those sub-arrays, the value is changed at the same index for all sub-arrays.

Is there a way to create a new object for each entry?

Answer Source

Array#fill won't help you, it accepts the value returned by emptyRow(), the already created object. You could use Array#map which accepts a function, although you won't be able to use the new Array() constructor. Here's the simplest way:

function emptyMatrix() {
  Array.apply(null, {length: 9}).map(emptyRow);
  // create the array            fill in values

Or, more generally:

function generateArray(n, valueFactory) {
  return Array.apply(null, {length: n}).map(valueFactory);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download