wtorek, 16 czerwca 2015

Arrays in JavaScript - how to create an array and fill it with numbers

Most common way (and fastest if array would be big, please check jsperf.com/array-magic-vs-for):
var arr = [];
var max = 100;
for (var i = 0; i < max; i++) {
  arr.push(i);
}

But if array wouldn't be so big, we can use:
var max = 7;
var arr = Array.apply(null, {length: max}).map(Number.call, Number);

Of course very often we need some specific values. Fortunately map() gives us many options:
var max = 9;
var arr1 = Array.
   apply(null, {length: max}).
   map(function(item, index){ return ++index;});
var arr2 = Array.
   apply(null, {length: max}).
   map(Function.call, Math.random);