微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/js/150291.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐