JS中的稀疏数组与密集数组

一、概念

密集数组: 占据连续的内存空间,数组元素之间紧密相连,不存在间隙

const arr = [1, 2, 3, 4, 5]

稀疏数组: 数组原素之间存在间隙

const arr = [1, 2, 3]
arr[9] = 9
arr // [1, 2, 3, empty × 6, 9]

二、特点

  • 对于稀疏数组中empty不能用filtermapforEach等方法处理
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

原因: 在这些方法中都一个ini 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)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值