0

I just found something is interesting in Javascript multidimensional array.

let arr = Array(3).fill([]);
arr[0].push('1');

I thought the result should be arr = [['1'], [], []], but got arr = [['1'], ['1'], ['1']].

If update a value as arr[2][0] = '*', expected array to be arr = [['1'], ['1'], ['*']], but got arr = [['*'], ['*'], ['*']].

So why Javascript multidimensional array work like this? How to just update a value in multidimensional array?

Justin
  • 307
  • 1
  • 4
  • 16
  • 1
    This is more a matter of the specifics of `.fill()` than multidimensional arrays. From the docs: *"If the first parameter is an object, each slot in the array will reference that object."* [Array.prototype.fill()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill#description) – pilchard Mar 16 '21 at 00:48

1 Answers1

0

From pichard's comment, I got the right result by doing as following:

let arr = Array(3).fill([]).map(obj => { return [] });
arr[0].push('1');
arr[2][0] = '*';

The result is arr = [['1'], [], ['*']]

Justin
  • 307
  • 1
  • 4
  • 16