gpt4 book ai didi

javascript - 当数组元素中的逗号不会影响数组的长度时

转载 作者:行者123 更新时间:2023-12-01 03:17:22 25 4
gpt4 key购买 nike

ECMAScript 2016 .

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.

但是


var a = [b=1,,]
console.log(a.length)//2
逗号前面是赋值表达式 (b=1),缺少的数组元素贡献了长度。我想知道为什么吗?
ECMAScript 表示不提供长度。我想知道逗号如何不贡献长度,除了在数组的末尾

最佳答案

逗号跟随一个计数元素,它不标记一个元素的开始。作为数组中最后一个的逗号是没有意义的,因为前面的元素已经被考虑在内。

您遗漏了解释的最后一句,这似乎回答了您的问题:

If an element is elided at the end of an array, that element does not contribute to the length of the Array.

它还表示数组开头或中间的空元素确实会影响数组长度(因为它们跟随计数的元素,即使它们是空的) .

如果只有这个:[,],则长度将为 1,因为数组开头的逗号之前有空的未定义元素。

你的例子:var a = [b=1,,] 只有 2 个元素而不是 3 个,因为第二个逗号后面没有任何内容。第一个逗号后面的空元素确实有贡献,因为它不在末尾,后面跟着第二个逗号,表明那里有一个索引,但里面什么也没有。这就像编写[b=1, undefined]。第二个逗号实际上是一个拼写错误。

关于javascript - 当数组元素中的逗号不会影响数组的长度时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45465910/

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