タイトルが示すように、ループ変数が にバインドされていない for インデックスを使用for-of
してループ本体を実行するのに、他の反復構造 ( 、など) は実行しないのはなぜですか?undefined
Array
forEach()
for-in
明確化:多くの人が質問を誤解しているため
次のことではありません。
(スパースにすることはできません) またはTypedArray
sを繰り返す他のクラス「正しく」反復する方法まばらArray
に(他のすべての方法は期待どおりに機能するようです)スキップでundefined
要素Array
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.
これは意図した動作ですか (はい) & なぜこのように設計されたのですか?