The for...of
statement creates a loop Iterating over iterable objects (including Array, Map, Set, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
for (variable of object) { statement }
variable
object
for...of
and for...in
The following example shows the difference between a for...of
loop and a for...in
loop. While for...in
iterates over property names, for...of
iterates over property values:
let arr = [3, 5, 7]; arr.foo = "hello"; for (let i in arr) { console.log(i); // logs "0", "1", "2", "foo" } for (let i of arr) { console.log(i); // logs "3", "5", "7" }
Array.prototype.forEach()
To get the same property values the for...of
loop would return, you can also use the Array.prototype.forEach() method:
let arr = [3, 5, 7]; arr.foo = "hello"; arr.forEach(function (element, index) { console.log(element); // logs "3", "5", "7" console.log(index); // logs "0", "1", "2" }); // or with Object.keys() Object.keys(arr).forEach(function (element, index) { console.log(arr[element]); // logs "3", "5", "7", "hello" console.log(arr[index]); // logs "3", "5", "7", undefined });
Iterating over DOM collections like : the following example adds a read
class to paragraphs that are direct descendants of an article:
// Note: This will only work in platforms that have // implemented NodeList.prototype[Symbol.iterator] let articleParagraphs = document.querySelectorAll("article > p"); for (let paragraph of articleParagraphs) { paragraph.classList.add("read"); }
You can also iterate over generators:
function* fibonacci() { // a generator function let [prev, curr] = [0, 1]; for (;;) { [prev, curr] = [curr, prev + curr]; yield curr; } } for (let n of fibonacci()) { // truncate the sequence at 1000 if (n > 1000) break; console.log(n); }
[1] From Chrome 29 to Chrome 37 this feature was available behind a preference. In chrome://flags/#enable-javascript-harmony, activate the entry “Enable Experimental JavaScript”.
[2] From Gecko 17 (Firefox 17 / Thunderbird 17 / SeaMonkey 2.14) to Gecko 26 (Firefox 26 / Thunderbird 26 / SeaMonkey 2.23 / Firefox OS 1.2) the iterator
property was used (bug 907077), and from Gecko 27 to Gecko 35 the "@@iterator"
placeholder was used. In Gecko 36 (Firefox 36 / Thunderbird 36 / SeaMonkey 2.33), the @@iterator
symbol got implemented (bug 918828).
Created by Mozilla Contributors, license: CC-BY-SA 2.5