0

Though I know what results it ends with but it's a really trap, kinda of anti-intuition of normal understanding of how these array API works.

Take a look: Case 1

const x = new Array(2).fill([]);
x[0].push("item 1")
x[1].push("item 2")

intention: initial an array with two empty sub-array, and push two different items into each.

expectation: x=[["item 1"], ["item 2"]]

reality: x=[["item 1", "item 2"], ["item 1", "item 2"]]

seems like, the "fill" function takes the same object of "[]", wired, isn't it?

Case 2

const x = new Array(3).map(
          (_, i) => `col_${i}`,
        );

intention: create an array of given length with default value of "col_[index]" for each item.

expectation: x=["col_0", "col_1", "col_2"]

reality: x=[null, null, null]

So it looks like "new Array()" is just has a length property but not really you can iterate over it.

Questions:

  1. It is really like a puzzle, anybody have insights into why it is designed in this way? Or just - well it is javascript, let's do whatever we like... :(
  2. For the above two intentions - what are the simplest ways you will make?
Shawn Cao
  • 117
  • 7
  • 1
    The second one is _not_ `[ null, null, null ]`. The behavior of [`new Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/Array#parameters) and [`map`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/map#description) _are documented_. `new Array(length)` is very old, and has drawbacks. Use ``Array.from({ length: 3 }, (_, i) => `col_${i}`)`` instead. – Sebastian Simon Jan 22 '22 at 07:23
  • found this one to be relevant - https://stackoverflow.com/questions/35578478/array-prototype-fill-with-object-passes-reference-and-not-new-instance – Shawn Cao Jan 22 '22 at 07:31

0 Answers0