之前看到知乎上的这道题:怎样不运用loop轮回,建立一个长度为100的数组,而且每一个元素的值即是它的下标?,在这个题目内里题主提到,他写了这么一段代码:
'use strict'
let arr = Array(100).map( (item,idx) => idx)
效果arr是一个有100个空位的数组:
这申明Array.prototype.map()
会跳过空位元素嘛。
然后我鄙人面的答案里看到这么一条:
Array.from(new Array(100), (item, idx) => idx)
//or the alternative
Array.from({length: 5}, (item, idx) => idx)
我本来是以为,这个一定也不可嘛,这俩都是用Array组织函数新建了一个满是空位的数组嘛,怎么会不一样呢?效果试了一下以后发明竟然成功地得到了数组。我最先疑心Array.from
的map函数的完成和Array.prototype.map
有不一样的处所。再加上MDN的文档也来扰乱:
Array.from(arrayLike[, mapFn[, thisArg]])
#arrayLike
An array-like or iterable object to convert to an array.
#mapFn
Optional. Map function to call on <every element of the array>.
#thisArg
Optional. Value to use as this when executing mapFn.
在这里mapFn
下面明白地指出mapFn
会挪用every element of the array
.
而在map
函数那里:
callback is invoked only for indexes of the array which have assigned values, including undefined. It is not called for missing elements of the array.
明白申明会跳过空位元素,所以我就想是否是这俩家伙的map要领自身不一致。
固然结论并没有这么凶猛 Orz…厥后我偶然间发明本来是因为Array.from()
要领会把数组的空位转为undefined
.也就是说数组空位元素的处置惩罚和map
要领的完成是无关的。
数组空位元素的处置惩罚
forEach()
,filter()
,every()
和some()
都邑跳过空位。map()
会跳过空位,但会保存这个值join()
和toString()
会将空位视为undefined
,而undefined
和null
会被处置惩罚成空字符串
// forEach要领
[,'a'].forEach((x,i) => log(i)); // 1
// filter要领
['a',,'b'].filter(x => true) // ['a','b']
// every要领
[,'a'].every(x => x==='a') // true
// some要领
[,'a'].some(x => x !== 'a') // false
// map要领
[,'a'].map(x => 1) // [,1]
// join要领
[,'a',undefined,null].join('#') // "#a##"
// toString要领
[,'a',undefined,null].toString() // ",a,,"
ES6则是明白将空位转为undefined
,Array.from
要领会将数组的空位转为undefined
,也就是说,这个要领不会疏忽空位:
Array.from(['a',,'b'])
// [ "a", undefined, "b" ]
扩大运算符(…)也会将空位转为undefined
:
[...['a',,'b']]
// [ "a", undefined, "b" ]
for...of
轮回也会遍历空位:
let arr = [, ,];
for (let i of arr) {
console.log(1);
}
// 1
// 1
entries()
、keys()
、values()
、find()
和findIndex()
会将空位处置惩罚成undefined
:
// entries()
[...[,'a'].entries()] // [[0,undefined], [1,"a"]]
// keys()
[...[,'a'].keys()] // [0,1]
// values()
[...[,'a'].values()] // [undefined,"a"]
// find()
[,'a'].find(x => true) // undefined
// findIndex()
[,'a'].findIndex(x => true) // 0
参考:阮一峰ES2015