1 2 3 4 5 6
Note that friends value doesn’t change.
Array.prototype.map return a new array for us. Immutability huh?
In some case, we might need to initialize array with a fix length so that we can iterate over it with method like
Array.prototype.map etc. So how do we initialize an array?
1. The new syntax
2. Array literal
Obviously, if we want to init an array with a fix length, the new syntax seems easier. Imagine how do we create array with length 100 with the array literal? Sure we can do something like:
1 2 3 4 5 6 7 8
But it’s not expressive. Compare this to:
Boom, short and clean. However, the array created is filled with undefined. Thus make it non-iterable.
1 2 3
So what is the solution
Here are some solutions implemented by myself and also collected from resources online.
1 2 3
With es6 now we have many additional array method. One of them can help us to achieve what we want.
1 2 3
Another cool feature from es6 will also complete our task.
This is also an es6 feature, so if compatibility is what you considering, please use polyfill.
4. Utility library
Using library like lodash can make our code looks cleaner.
Protip: If you use node, you can require smallest lodash.range package from npm.
We had seen 4 solutions to do this in JavaScirpt. By using
Function.proptotype.apply we can initialize an array with a fix length or incremental value. Moreover, we can achieve the same thing more elegant by using es6 feature. Finally, never forget library like lodash or underscore too =)