在原生js中,建立数组的常见方式有两种:Array() 或 new Array() 和 [] 方式.数组
构造函数建立数组和字面量定义数组的差别不谈,app
当咱们须要给建立数组赋初始值时,若是量少的话,能够直接经过函数
let arr = [2,4] 的方式建立;spa
而当量大而重复的时候,能够经过如下的方式建立:code
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]ip
等同于:get
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]class
若是须要递增赋值的话:构造函数
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]
以上的语法也能够写成:
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]
可能有人会疑惑,为何要Array(...Array(20))这么麻烦的来建立数组呢,直接Array(20)再经过map()来赋值不能够吗?
这是由于直接经过Array(20)的方式建立的数组,只有长度没有索引值,
Array(20)
(20) [empty × 20]
Array(20)[2] //undefined
2 in Array(20) //false
而map
()方法会给原数组中的每一个元素都按顺序调用一次 callback
函数。callback
每次执行后的返回值(包括 undefined
)组合起来造成一个新数组。
<strong>callback
函数只会在有值的索引上被调用;那些历来没被赋过值或者使用 delete
删除的索引则不会被调用。</strong>
再看:
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
因此就能够调用map()方法了
另外,直接经过
Array(20).fill(2)
(20) [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]
也能很轻松的赋值了