javascript数组 – 什么是真正的表达式?

前端之家收集整理的这篇文章主要介绍了javascript数组 – 什么是真正的表达式?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
创建3个未定义的空数组.
var a1 = [,];
var a2 = new Array(3);

来自JavaScript:The Definitive Guide,

0 in a1 //true
0 in a2 //false

但是,在现实世界的浏览器中,获得不同的结果. (IE8和Chrome 33 ……)

0 in a1 //false
0 in a2 //false

这是真的,书还是现实世界?

解决方法

看起来这本书是错的.从 specification可以看出,[,]不会向数组添加任何值:

The production ArrayLiteral : [ Elisionopt ] is evaluated as follows:

  1. Let array be the result of creating a new object as if by the expression new Array() where Array is the standard built-in constructor with that name.
  2. Let pad be the result of evaluating Elision; if not present,use the numeric value zero.
  3. Call the [[Put]] internal method of array with arguments “length”,pad,and false.
  4. Return array.

(“Elisions”是表达式之前或之后的.)

简单来说:

>创建一个空数组
>从1开始评估,基本上只是计算它们.
那么,结果为3.
>然后将数组的长度设置为结果(例如3).

而这正是新的Array(3)正在做的事情.

对于省略元素的描述也不太正式:

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.

猜你在找的JavaScript相关文章