一、概念
密集数组: 占据连续的内存空间,数组元素之间紧密相连,不存在间隙
const arr = [1, 2, 3, 4, 5]
稀疏数组: 数组原素之间存在间隙
const arr = [1, 2, 3]
arr[9] = 9
arr // [1, 2, 3, empty × 6, 9]
二、特点
- 对于稀疏数组中empty不能用
filter
、map
、forEach
等方法处理
const arr = [1, 2, 3]
arr[9] = 9
arr // [1, 2, 3, empty × 6, 9]
arr.filter(item=> item === undefined) // []
arr.map(item=> typeof item) // (10) ['number', 'number', 'number', empty × 6, 'number']
1 in arr
// true
9 in arr
// true
5 in arr
// false
原因: 在这些方法中都一个in
(i in this
)判断
if (!Array.prototype.filter){
Array.prototype.filter = function(func, thisArg) {
'use strict';
if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
throw new TypeError();
var len = this.length >>> 0,
res = new Array(len), // preallocate array
t = this, c = 0, i = -1;
if (thisArg === undefined){
while (++i !== len){
// checks to see if the key was set
if (i in this){
if (func(t[i], i, t)){
res[c++] = t[i];
}
}
}
}
else{
while (++i !== len){
// checks to see if the key was set
if (i in this){
if (func.call(thisArg, t[i], i, t)){
res[c++] = t[i];
}
}
}
}
res.length = c; // shrink down array to proper size
return res;
};
}
三、数组的创建
- 稀疏数组
const list = new Array(6)
list // (6) [empty × 6]
- 密集数组
方法一
const arr1 = Array.apply(null, Array(3))
arr1
//(3) [undefined, undefined, undefined]
方法二
const arr2 = Array.from({length: 3})
arr2
// (3) [undefined, undefined, undefined]
四、作用
- 密集型数组初始化数据
//const dataList = Array.from({length: 3}, (item, index) //=> {
// return {
// id: index,
// info: 'xxx' + index
// }
//})
const dataList =Array.apply(null, Array(3)).map((item, index) => {
return {
id: index,
info: 'xxx' + index
}
})
dataList
//(3) [{…}, {…}, {…}]
//0: {id: 0, info: 'xxx0'}
//1: {id: 1, info: 'xxx1'}
//2: {id: 2, info: 'xxx2'}
//length: 3
//[[Prototype]]: Array(0)