ECMAScript6(es6) 规格:数组的空位(map方法)
下面再看另一个例子。
const a1 = [undefined, undefined, undefined];
const a2 = [, , ,];
a1.length // 3
a2.length // 3
a1[0] // undefined
a2[0] // undefined
a1[0] === a2[0] // true
上面代码中,数组a1
的成员是三个undefined
,数组a2
的成员是三个空位。这两个数组很相似,长度都是3,每个位置的成员读取出来都是undefined
。
但是,它们实际上存在重大差异。
0 in a1 // true
0 in a2 // false
a1.hasOwnProperty(0) // true
a2.hasOwnProperty(0) // false
Object.keys(a1) // ["0", "1", "2"]
Object.keys(a2) // []
a1.map(n => 1) // [1, 1, 1]
a2.map(n => 1) // [, , ,]
上面代码一共列出了四种运算,数组a1
和a2
的结果都不一样。前三种运算(in
运算符、数组的hasOwnProperty
方法、Object.keys
方法)都说明,数组a2
取不到属性名。最后一种运算(数组的map
方法)说明,数组a2
没有发生遍历。
为什么a1
与a2
成员的行为不一致?数组的成员是undefined
或空位,到底有什么不同?
规格的12.2.5小节《数组的初始化》给出了答案。
“Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (i.e., a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.”
翻译如下。
"数组成员可以省略。只要逗号前面没有任何表达式,数组的
length
属性就会加1,并且相应增加其后成员的位置索引。被省略的成员不会被定义。如果被省略的成员是数组最后一个成员,则不会导致数组length
属性增加。”
上面的规格说得很清楚,数组的空位会反映在length
属性,也就是说空位有自己的位置,但是这个位置的值是未定义,即这个值是不存在的。如果一定要读取,结果就是undefined
(因为undefined
在JavaScript语言中表示不存在)。
这就解释了为什么in
运算符、数组的hasOwnProperty
方法、Object.keys
方法,都取不到空位的属性名。因为这个属性名根本就不存在,规格里面没说要为空位分配属性名(位置索引),只说要为下一个元素的位置索引加1。
至于为什么数组的map
方法会跳过空位,请看下一节。
数组的map方法
规格的22.1.3.15小节定义了数组的map
方法。该小节先是总体描述map
方法的行为,里面没有提到数组空位。
后面的算法描述是这样的。
- Let
O
beToObject(this value)
.ReturnIfAbrupt(O)
.- Let
len
beToLength(Get(O, "length"))
.ReturnIfAbrupt(len)
.- If
IsCallable(callbackfn)
isfalse
, throw a TypeError exception.- If
thisArg
was supplied, letT
bethisArg
; else letT
beundefined
.- Let
A
beArraySpeciesCreate(O, len)
.ReturnIfAbrupt(A)
.- Let
k
be 0.- Repeat, while
k
<len
a. LetPk
beToString(k)
.
b. LetkPresent
beHasProperty(O, Pk)
.
c.ReturnIfAbrupt(kPresent)
.
d. IfkPresent
istrue
, then
d-1. LetkValue
beGet(O, Pk)
.
d-2.ReturnIfAbrupt(kValue)
.
d-3. LetmappedValue
beCall(callbackfn, T, «kValue, k, O»)
.
d-4.ReturnIfAbrupt(mappedValue)
.
d-5. Letstatus
beCreateDataPropertyOrThrow (A, Pk, mappedValue)
.
d-6.ReturnIfAbrupt(status)
.
e. Increasek
by 1.- Return
A
.
翻译如下。
- 得到当前数组的
this
对象- 如果报错就返回
- 求出当前数组的
length
属性- 如果报错就返回
- 如果map方法的参数
callbackfn
不可执行,就报错- 如果map方法的参数之中,指定了
this
,就让T
等于该参数,否则T
为undefined
- 生成一个新的数组
A
,跟当前数组的length
属性保持一致- 如果报错就返回
- 设定
k
等于0- 只要
k
小于当前数组的length
属性,就重复下面步骤
a. 设定Pk
等于ToString(k)
,即将K
转为字符串
b. 设定kPresent
等于HasProperty(O, Pk)
,即求当前数组有没有指定属性
c. 如果报错就返回
d. 如果kPresent
等于true
,则进行下面步骤
d-1. 设定kValue
等于Get(O, Pk)
,取出当前数组的指定属性
d-2. 如果报错就返回
d-3. 设定mappedValue
等于Call(callbackfn, T, «kValue, k, O»)
,即执行回调函数
d-4. 如果报错就返回
d-5. 设定status
等于CreateDataPropertyOrThrow (A, Pk, mappedValue)
,即将回调函数的值放入A
数组的指定位置
d-6. 如果报错就返回
e.k
增加1- 返回
A
仔细查看上面的算法,可以发现,当处理一个全是空位的数组时,前面步骤都没有问题。进入第10步的b时,kpresent
会报错,因为空位对应的属性名,对于数组来说是不存在的,因此就会返回,不会进行后面的步骤。
const arr = [, , ,];
arr.map(n => {
console.log(n);
return 1;
}) // [, , ,]
上面代码中,arr
是一个全是空位的数组,map
方法遍历成员时,发现是空位,就直接跳过,不会进入回调函数。因此,回调函数里面的console.log
语句根本不会执行,整个map
方法返回一个全是空位的新数组。
V8引擎对map
方法的实现如下,可以看到跟规格的算法描述完全一致。
function ArrayMap(f, receiver) {
CHECK_OBJECT_COERCIBLE(this, "Array.prototype.map");
// Pull out the length so that modifications to the length in the
// loop will not affect the looping and side effects are visible.
var array = TO_OBJECT(this);
var length = TO_LENGTH_OR_UINT32(array.length);
return InnerArrayMap(f, receiver, array, length);
}
function InnerArrayMap(f, receiver, array, length) {
if (!IS_CALLABLE(f)) throw MakeTypeError(kCalledNonCallable, f);
var accumulator = new InternalArray(length);
var is_array = IS_ARRAY(array);
var stepping = DEBUG_IS_STEPPING(f);
for (var i = 0; i < length; i++) {
if (HAS_INDEX(array, i, is_array)) {
var element = array[i];
// Prepare break slots for debugger step in.
if (stepping) %DebugPrepareStepInIfStepping(f);
accumulator[i] = %_Call(f, receiver, element, i, array);
}
}
var result = new GlobalArray();
%MoveArrayContents(accumulator, result);
return result;
}