【发布时间】:2019-04-27 23:51:09
【问题描述】:
正如标题所说,为什么for-of 运行循环体,循环变量 绑定到undefined 用于不在Array 中的索引,而其他迭代构造(forEach() 、for-in 等)不要?
澄清:许多人误解了这个问题
不是关于:
-
迭代(不能是稀疏的)或TypedArrays任何其他类 -
如何在稀疏的(其他所有方法似乎都以预期的方式工作)Array上“正确”迭代 -
在Array中跳过undefined元素
下面的非正式描述found on MDN不正确吗?
for...of语句 [...] 调用自定义迭代挂钩,其中包含要针对对象的每个不同属性的值执行的语句。
即不存在的属性也会调用它。
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) 以及为什么以这种方式设计?
【问题讨论】:
标签: javascript iteration sparse-matrix for-of-loop