JS โฉ object โฉ built-in โฉ Array โฉ iterating arrays
// โญ๏ธ for-of: treats "holes" as undefined for (const value of array) {} for (const [index, value] of array.entries()) {} // with index // โญ๏ธ forEach: ignores "holes" arr.forEach(value => ...) // .forEach() method
Unlike the for-of loop, forEach() is aware of sparse arrays and does not invoke the function for nonexistent elements.
iterating arrays
for-of loop
arr.forEach() method
for-of vs. forEach
๐ for-of vs. forEach.
let a = []; // sparse array a[1] = 'hi'; a[5] = 'world'; let forofCount = 0; let foreachCount = 0; // โญ๏ธ for-of: treats "holes" as `undefined`. for (const value of a) { forofCount += 1; console.log(forofCount, value); } // 1 undefined, 2 'hi', 3 undefined, ... 6 'world' // โญ๏ธ forEach: ignores "holes". a.forEach(value => { foreachCount += 1; console.log(foreachCount, value); }) // 1 'hi', 2 'world'
JS.info โฉ iterables
JavaScript: The Definitive Guide โฉ 7.6 Iterating Arrays
Last updated 2 years ago