Array(5)gives you an array with length 5 but no values, hence you can't iterate over it.Array.apply(null, Array(5)).map(function () {})gives you an array with length 5 and undefined as values, now it can be iterated over.Array.apply(null, Array(5)).map(function (x, i) { return i; })gives you an array with length 5 and values 0,1,2,3,4.Array(5).forEach(alert)does nothing,Array.apply(null, Array(5)).forEach(alert)gives you 5 alertsES6gives usArray.fromso now you can also useArray.from(Array(5)).forEach(alert)If you want to initialize with a certain value, these are good to knows...
Array.from('abcde'),Array.from('x'.repeat(5))
orArray.from({length: 5}, (v, i) => i) // gives [0, 1, 2, 3, 4]
With ES2015 .fill() you can now simply do:
// `n` is the size you want to initialize your array
// `0` is what the array will be filled with (can be any other value)
Array(n).fill(0)
Which is a lot more concise than Array.apply(0, new Array(n)).map(i => value)
It is possible to drop the 0 in .fill() and run without arguments, which will fill the array with undefined. (However, this will fail in Typescript)
Array.size() is not a valid method
Always use the length property
There is a library or script adding the size method to the array prototype since this is not a native array method. This is commonly done to add support for a custom getter. An example of using this would be when you want to get the size in memory of an array (which is the only thing I can think of that would be useful for this name).
Underscore.js unfortunately defines a size method which actually returns the length of an object or array. Since unfortunately the length property of a function is defined as the number of named arguments the function declares they had to use an alternative and size was chosen (count would have been a better choice).
.size() is not a native JS function of Array (at least not in any browser that I know of).
.length should be used.
If
.size() does work on your page, make sure you do not have any extra libraries included like prototype that is mucking with the Array prototype.
or
There might be some plugin on your browser that is mucking with the Array prototype.