1.8 KiB
1.8 KiB
title |
---|
For...Of Loop |
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
}
Description | |
---|---|
variable | On each iteration a value of a different property is assigned to variable. |
object | Object whose enumerable properties are iterated. |
Examples
Array
let arr = [ "fred", "tom", "bob" ];
for (let i of arr) {
console.log(i);
}
// Output:
// fred
// tom
// bob
Map
const m = new Map();
m.set(1, "black");
m.set(2, "red");
for (let n of m) {
console.log(n);
}
// Output:
// [1, "black"]
// [2, "red"]
Set
const s = new Set();
s.add(1);
s.add("red");
for (let n of s) {
console.log(n);
}
// Output:
// 1
// red
Arguments object
// your browser must support for..of loop
// and let-scoped variables in for loops
function displayArgumentsObject() {
for (let n of arguments) {
console.log(n);
}
}
displayArgumentsObject(1, 'red');
// Output:
// 1
// red