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:
- 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... :(
- For the above two intentions - what are the simplest ways you will make?