Js中数组空位问题
JavaScript
中数组空位指的是数组中的empty
,其表示的是在该位置没有任何值,而且empty
是区别于undefined
的,同样empty
也不属于Js
的任何数据类型,并且在JavaScript
版本以及各种方法对于空位的处理也有不同,所以建议避免在数组中出现空位。
描述
在JavaScript
的数组是以稀疏数组的形式存在的,所以当在某些位置没有值时,就需要使用某个值去填充。当然对于稀疏数组在各种浏览器中会存在优化的操作,例如在V8
引擎中就存在快数组与慢数组的转化,此外在V8
中对于empty
的描述是一个空对象的引用。在Js
中使用Array
构造器创建出的存在空位的问题,默认并不会以undefined
填充,而是以empty
作为值,需要注意的是,空位并不是undefined
,undefined
表示的是没有定义,但是本身undefined
就是一个基本数据类型,是一个值,而是empty
表示了该处没有任何值,是一个完全为空的位置。
1 2 3 4 5
| console.log([,,,]); console.log(new Array(3)); console.log([undefined, undefined, undefined]); console.log(0 in [undefined, undefined, undefined]); console.log(0 in [,,,]);
|
方法处理
ECMA262V5
中对空位的处理就已经开始不一致了,在大多数情况下会忽略空位,例如forEach()
、for in
、filter()
、every()
和some()
都会跳过空位,map()
会跳过空位,但会保留这个值,join()
和toString()
会将空位与undefined
以及null
处理成空字符串。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| [1, , 2].forEach(v => console.log(v));
for(let key in [1, , 2]){ console.log(key); }
console.log([1, , 2].filter(v => true));
console.log([1, , 1].every(v => v === 1));
console.log([1, , 1].some(v => v !== 1));
console.log([1, , 1].map(v => 11));
console.log([1, , 1, null, undefined].join("|"));
console.log([1, , 1, null, undefined].toString());
|
ECMA262V6
则是将空位转为undefined
,例如Array.form()
方法会将数组的空位转为undefined
,扩展运算符也会将空位转为undefined
,copyWithin()
会连同空位一起拷贝,for of
循环也会遍历空位并将值作为undefined
,includes()
、entries()
、keys()
、values()
、find()
和findIndex()
等会将空位处理成undefined
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| console.log(Array.from([1, , 2]));
console.log([...[1, , 2]]);
console.log([1, , 2].copyWithin());
for(let key of [1, , 2]){ console.log(key); }
console.log([, , ,].includes(undefined));
console.log([...[1, , 2].entries()]);
console.log([...[1, , 2].keys()]);
console.log([...[1, , 2].values()]);
console.log([, , 1].find(v => true));
console.log([, , 1].findIndex(v => true));
|
参考
1 2 3 4 5 6 7
| https://www.zhihu.com/question/60919509 https://juejin.im/post/6844903917738786829 https://segmentfault.com/a/1190000004680060 https://xmoyking.github.io/2016/12/17/js-framework2/ https://juejin.im/post/6844904047934373896#heading-12 https://blog.csdn.net/qq_30100043/article/details/53308524 https://blog.csdn.net/weixin_43342105/article/details/108638001
|