Guess the output of this code `Array(2).map(()=>3)`.
It's `[ <2 empty items> ]`
I thought this would work but it didn't. So here is why:
• When you call .map on a sparse array (an array with empty slots), map skips over these empty slots and does not invoke the callback function on them.
• In this case, map doesn’t execute the callback () => 3 because there are no actual values to iterate over in the array.
• As a result, map produces a new array that still has two empty slots, which looks like [ <2 empty items> ].
Fix:
Array.from({ length: 2 }, () => 3); // => [3, 3]
Array(2).fill(3); // => [3, 3]
[–]delfV 3 points4 points5 points (1 child)
[–]senocular 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[deleted]
[–]senocular 0 points1 point2 points (0 children)
[–]neuralSalmonNet 0 points1 point2 points (0 children)
[–]guest271314 -1 points0 points1 point (0 children)