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.

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...