Stumbled upon this while exploring array methods on a plane. Oh, the places we go when we're bored. :)
var initializedArray = new Array(30).join(null).split(null).map(function(item, index){ return index; });
.map() and null to win! I like null because switching to a string of type up with "0" or any other value is confusing. I think it is more obvious that we are doing something else.
Note that .map() skips uninitialized values. This is why new Array(30).map(function(item, index){return index}); does not work. The new .fill() method is preferred if available, however browser support should be marked as 8/23/2015 .
Desktop (basic support)
- Chrome 45 (36 1 )
- Firefox (Gecko) 31 (31)
- Internet Explorer is not supported
- Opera is not supported
- Safari 7.1
From MDN :
[1, 2, 3].fill(4); // [4, 4, 4] [1, 2, 3].fill(4, 1); // [1, 4, 4] [1, 2, 3].fill(4, 1, 2); // [1, 4, 3] [1, 2, 3].fill(4, 1, 1); // [1, 2, 3] [1, 2, 3].fill(4, -3, -2); // [4, 2, 3] [1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3] Array(3).fill(4); // [4, 4, 4] [].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}