gpt4 book ai didi

javascript array - 什么是真正的表达?

转载 作者:数据小太阳 更新时间:2023-10-29 05:12:42 24 4
gpt4 key购买 nike

创建 3 个未定义的空数组。

var a1 = [,,,];
var a2 = new Array(3);

来自 JavaScript:权威指南,

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.

(“省略号”是 , 前后没有表达式。)

简单来说:

  • 创建一个空数组
  • 评估 ,,基本上就是从 1 开始计算它们。所以 ,,, 结果是 3。
  • 然后将数组的长度设置为结果(例如3)。

这正是 new 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 array - 什么是真正的表达?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21297040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com