gpt4 book ai didi

javascript - 为什么 for-of 不跳过稀疏数组的空槽? [JavaScript]

转载 作者:行者123 更新时间:2023-12-02 23:45:18 26 4
gpt4 key购买 nike

正如标题所说,为什么for-of使用绑定(bind)到 undefined循环变量运行循环体对于不在 Array 中的索引,而其他迭代结构( forEach()for-in 等)则不然?

澄清:很多人误解了这个问题

不是关于:

  • 迭代TypedArray s(不能稀疏)或任何其他类
  • 如何“正确”迭代稀疏 Array (所有其他方法似乎都按预期方式工作)
  • 跳过 undefined Array 中的元素
<小时/>

以下是非正式描述 found on MDN不正确?

The for...of statement [...] invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

即对于不存在的属性也会调用它。

const sparse = [0, 1, 2] // Was [0, , 2], but some are unfamiliar with this syntax 
// or think it creates the array [0, undefined, 2]
delete sparse[1]
for (let e of sparse) console.log('for-of', e)
// Contrast with:
sparse.forEach(e => console.log('forEach', e))
for (let i in sparse) console.log('for-in', sparse[i])
console.log('map', sparse.map(e => e)) // Note, prints incorrectly in the snippet
// console, check browser console
// etc.

这是预期的行为 ( Yes ) 以及为什么要这样设计?

最佳答案

for..of 调用数组迭代器方法,描述为in the spec .

(2) Let iterator be ObjectCreate(%ArrayIteratorPrototype%, «‍[[IteratedObject]], [[ArrayIteratorNextIndex]], [[ArrayIterationKind]]»).

(4) Set iterator’s [[ArrayIteratorNextIndex]] internal slot to 0.

然后,当迭代器迭代完毕后,在 22.1.5.2.1 %ArrayIteratorPrototype%.next: 中:

(6) Let index be the value of the [[ArrayIteratorNextIndex]] internal slot of O.

(10) If index ≥ len, then

(10) (a) Set the value of the [[IteratedObject]] internal slot of O to undefined.

(10) (b) Return CreateIterResultObject(undefined, true).

(11) Set the value of the [[ArrayIteratorNextIndex]] internal slot of O to index+1.

(create iterator result object whose value is array[index])

换句话来说,迭代器从索引 0 开始迭代,每次调用 .next() 时索引都会增加 1。它不会检查数组是否在该索引处确实一个项目(稀疏数组不会) - 它只是检查索引是否小于.length 数组。

另一方面,使用 for..in 时,所有可枚举属性都会被迭代,并且数组自身的可枚举属性不包括> 稀疏数组索引。

const sparse = [0, , 2];
console.log(sparse.hasOwnProperty('0'));
console.log(sparse.hasOwnProperty('1'));

所以是的,这是预期的行为。

关于javascript - 为什么 for-of 不跳过稀疏数组的空槽? [JavaScript],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55885848/

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