1

I have a for loop like so:

var myary = [];
for(i=0; i<3; i++){
  myary[i] = i;
}
//yields [0, 1, 2]

I'd like to accomplish the same with myary.apply() or a functional equivalent, but I am not familiar with generating arithmetic sequences via functional methods in JavaScript. Is this possible?

jml
  • 1,745
  • 6
  • 29
  • 55

1 Answers1

1

There's no clean and easy functional solution in ES5. Here's the simplest I have:

var myary = Array.apply(0,Array(N)).map(function(_,i){return i});

Edit: Be careful that expressions of this kind, while being sometimes convenient, can be very slow. This commit I made was motivated by performance issues. An old style and boring for loop can often be much faster.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758