In the native js, there are two common ways to create an array: Array () or new Array () and [] mode.
Constructor creates an array of differences in definitions and literal array aside,
When we need to create an array assigned an initial value, if less, you can directly through
Creating let arr = [2,4] manner;
And when large and repetitive, you can create the following way:
Array.apply(null,{length:20}).map(()=>2)
//(20) [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
Equivalent to:
Array.apply(null,Array(20)).map(()=>2)
//(20) [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
If you need to increment the assignment of words:
Array.apply(null,{length:20}).map((v,i)=>i)
(20) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Above syntax can also be written as:
Array(...Array(20)).map((v,i)=>i)
(20) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Some may wonder why Array (... Array (20)) so much trouble to create an array of it, directly Array (20) through the map () to assign not it?
This is because the array Array (20) by creating a direct way, and not only the length of the index value,
Array(20)
(20) [empty × 20]
Array(20)[2] //undefined
2 in Array(20) //false
And map
() methods will give the original of each element in the array in order to call a callback
function. callback
Each returned value is performed (including undefined
) combined to form a new array.
<strong> callback
function will only be called on the index has value; those who had never been assigned a value or use delete
to delete the index will not be called. </ strong>
Look:
Array(...Array(20))
(20) [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined]
2 in Array(...Array(20)) //true
So you can call the map () method of