javascript稀疏数组(sparse array)

<h1>
1.什么是稀疏数组
</h1>
在java,c++中数组是一段连续的存储空间,元素与元素之间没有空隙,但在js中允许存在有空隙的数组,这就是稀疏数组(sparse array)。稀疏数组就是包含从0开始的不连续索引的数组。
<h1>
2.稀疏数组实例
</h1>
先看个例子

var arr = new Array(3);
arr[100]=1;
console.log(arr.length);
arr.forEach(function(x,i){
console.log(x);});

输出为

101
1

这样就创建了一个稀疏数组,遍历它是js会跳过这些空隙,但是当我们输出数组中空隙位置的值时

var arr = new Array(3);
arr[100]=1;
console.log(arr.length);
console.log(arr[0]);
arr.forEach(function(x,i){
console.log(x);});

输出为

101
undefined
1

这里的undefined指不存在和在数组直接量中省略值是产生的undefined是不一样的,后者是值为undefined
两者的区别可以通过in操作符检测

var a1=[,,]
var a2=new Array(3);
0 in a1;
0 in a2;

第一个判断为true,因为a1 为[undefined,undefined,undefined]
第二个判断为false,因为 a2 在索引0初不存在元素

*需要注意的是在省略数组直接量时使用连续的逗号,如[1,,3]时得到的是稀疏数组
<h1>
3.压缩稀疏数组
</h1>
js中的数组一般都是稀疏数组,通常来说稀疏数组的遍历较为困难,我们可以通过filter()方法压缩其中的空隙,因为filter会跳过空隙,返回密集的数组

sparse.filter(function(x){
return true;
});

*同样可以使用filter()方法去除数组中的null和undefined

arr.filter(function(x){
return x!= undefined && x!= null;
});

<h1>
4.创建密集数组
</h1>
压缩稀疏数组不如直接创建一个密集数组

var sparse = new Array(3);
var dense = Array.apply(null, Array(3));
sparse.forEach(function(x,i){
console.log('sparse :'+i+x);});
dense.forEach(function(x,i){
console.log('dense :'+i+x);});

数组dense为密集数组,这段代码输出为

dense: 0 undefined
dense: 1 undefined
dense: 2 undefined

<h1>
5.想法
</h1>
作为java起手的程序员,习惯了连续的数组,也习惯将js中的数组转化为密集数组使用,避免一些麻烦。但实际上js中没有类似java中的数组,因为js中的数组根本就没有索引,js中的“索引”其实不是数字是字符串,因为js的对象就是字符串到任意值的键值对,数组作为一种对象数据类型自然不例外。

    原文作者:平壤艺术饭店
    原文地址: https://www.jianshu.com/p/4bce06e283cf
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞