JS64 数组中的空位
JavaScript中数组有空位的概念,也就是一个数组的位置上没有任何的值
数组中的空位
生成的方式有四种:
(1)直接定义
1 | let arr = [1, , 3]; // [1, empty, 3] |
(2)删除属性
1 | let arr = [1]; |
(3)使用new Array方法
1 | new Array(2); // [empty, empty]; |
可以使用ES6的
Array.of代替new Array,当参数个数不同时,它的行为更一致
(4)定义数组长度
1 | let arr = []; |
辨别空位和undefined
空位并不等于undefined和null,如果数组的一个位置上是undefined或者null,那么它依然有值。但是我们如果直接用数组下标读取数组的空位,得到的结果却是undefined:
1 | const arr = new Array(2); |
如何区别数组成员是空位还是undefined呢?可以使用hasOwnProperty方法或者in运算符,二者对于undefined和null都返回true,但是对于空位,由于根本没有值,所以会返回false:
1 | const arr = [undefined, ,]; // [undefined, empty]; |
数组方法对空位的处理
数组中的各种原生方法对空位的处理并不相同,有下面集中处理方式:
(1)作为undefined处理
Array.from、结构运算符...、for...of、fill方法都会将空位作为undefined处理
1 | const arr = new Array(4); |
(2)跳过
every/filter/forEach/some/find/indexOf/都会跳过空位
(3)其他
map方法会跳过空位,但是在结果中保留这个值Object.keys()方法不会取到空位的下标join方法会当做空字符串对待,返回',,,'sort方法会将empty的元素排到最后
练习
不用for方法,创建一个长度为100的数组,每个元素的值等于它的下标:
1 | Array.from({length: 100}, (v, index) => index); |