1

This is purely a flexibility exercise with JavaScript. I'm attempting to create an array of integers with Javascript without a loop and in this particular fashion:

var a = Array(100).map(function(x, y) { return y + 1 });

I would expect and Array of integers 1 - 100. Instead it remains undefined * 100? I can't even console.log from within the map function?

I understand from this great post Sequences using JavaScript Array that the below does accomplish the goal using Array.apply, I just understand why its needed?

var a = Array.apply(0, Array(100)).map(function(x,y) { return y + 1 }); a

Thanks for any insight :)

Dom
  • 38,906
  • 12
  • 52
  • 81
micahblu
  • 4,924
  • 5
  • 27
  • 33

1 Answers1

1

It's mainly for memory space optimization purpose, sparse arrays take less space in memory.

It kinds of "flags" with undefined so that you can do this kind of stuff without exploding memory space:

var a = [];

a[2014] = 0;
console.log(a.length); // 2015
console.log(a); // [undefined x 2014, 0]
axelduch
  • 10,769
  • 2
  • 31
  • 50
  • This does not answer the question of why `map` behaves the way it does here. –  Dec 26 '14 at 04:25