I'm trying to generate an array. Here's a simplified snippet of where I'm having a problem:
//should return an array with 10 elements with values of 0
var arr = Array(10).map(function() {return 0;});
console.log(arr.length); //returns 10
console.log(arr); //empty array
I understand that using Array(length)
returns an array with length
elements that are set to undefined
. I suspect .map()
is skipping over undefined
elements, but am not 100% sure about it.
What can I do to get the intended results? I know I can accomplish the same thing with a loop, but I would really like to use .map()
if possible.
--Update--
Can anyone explain why this works?
var arr = Array(10).join().split(',').map(function() {return 0;});
-edit- Disregard the update. I figured out why it works.