一、数组的创建
在讨论数组初始化之前,首先要知道数组的两种创建方式:
- 构造函数的创建方式 const a = new Array(2)
- 数组字面量语法 const b = [1, 1]
以上两种数组创建的方式都可能产生数组空位,例如:
const s1 = new Array(10)
上述虽然创建了一个长度为10的数组,但是在控制台打印的结果为:
(10) [empty × 10]
这里的empty就是数组中的空位,通常含有数组空位的数组称为稀疏数组,相反的,没有数组空位的数组称为密集数组。那么数组空位会造成什么影响呢?
const s2 = s1.map(() => 1)
上述代码中,我们想通过map方法对s1进行遍历返回一个值全为1的数组,但是最终s2打印出来仍然是一个含有10个数组空位的数组。
这里可以查看V8中关于map方法的实现:
function ArrayMap(f, receiver) {
CHECK_OBJECT_COERCIBLE(this, "Array.prototype.map");
// Pull out the length so that modifications to the length in the
// loop w