1. 數(shù)組字面量末尾的逗號(hào)
ES6 P142 12.2.5 Array Initializer
NOTE
An ArrayLiteral is an expression describing the initialization of an Array object, using a list, of zero or more expressions each of which represents an array element, enclosed in square brackets. The elements need not be literals; they are evaluated each time the array initializer is evaluated.
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.
因此,[,]會(huì)初始化為[undefined × 1],[,,]會(huì)初始化為[undefined × 2]
2. 關(guān)于空位
ES6 P400 22.1.1.2 Array (len)
This description applies if and only if the Array constructor is called with exactly one argument.
- Let numberOfArgs be the number of arguments passed to this function call.
- Assert: numberOfArgs = 1.
- If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget.
- Let proto be GetPrototypeFromConstructor(newTarget, "%ArrayPrototype%").
- ReturnIfAbrupt(proto).
- Let array be ArrayCreate(0, proto).
- If Type(len) is not Number, then
a. Let defineStatus be CreateDataProperty(array, "0", len).
b. Assert: defineStatus is true.
c. Let intLen be 1. - Else,
a. Let intLen be ToUint32(len).
b. If intLen ≠ len, throw a RangeError exception. - Let setStatus be Set(array, "length", intLen, true).
- Assert: setStatus is not an abrupt completion.
- Return array.
我們知道Array(2)會(huì)創(chuàng)建一個(gè)包含2個(gè)空位的數(shù)組。
具體步驟是,在第6步創(chuàng)建了一個(gè)長(zhǎng)度為0的數(shù)組,然后在第9步修改了這個(gè)數(shù)組的length屬性。
注:
(1)Set(array, "length", intLen, true),可參考
P49 7.3.3 Set (O, P, V, Throw)
The abstract operation Set is used to set the value of a specific property of an object. The operation is called with arguments O, P, V, and Throw where O is the object, P is the property key, V is the new value for the property and Throw is a Boolean flag. This abstract operation performs the following steps:
- Assert: Type(O) is Object.
- Assert: IsPropertyKey(P) is true.
- Assert: Type(Throw) is Boolean.
- Let success be O.[[Set]](P, V, O).
- ReturnIfAbrupt(success).
- If success is false and Throw is true, throw a TypeError exception.
- Return success.
(2)直接設(shè)置length屬性,可以產(chǎn)生空位
var a=[];
a.length //0
a.length=2;
a //[undefined × 2]
a.push(0); //[undefined × 2, 0]
a.unshift(0); //[0, undefined × 2, 0]