[JavaScript] [,]与[,,]
1. 数组字面量末尾的逗号
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.
因此,[,]会初始化为[undefined × 1],[,,]会初始化为[undefined × 2]
2. 关于空位
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)会创建一个包含2个空位的数组。
具体步骤是,在第6步创建了一个长度为0的数组,然后在第9步修改了这个数组的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)直接设置length属性,可以产生空位
var a=[];
a.length //0
a.length=2;
a //[undefined × 2]
a.push(0); //[undefined × 2, 0]
a.unshift(0); //[0, undefined × 2, 0]