The new for of
loop is designed to work exclusively with iterable objects. The loop calls the next
function behind the scenes and exits when the done
property is true
.
for ( let n of [1,2,3] ) {
console.log(n);
}
// 1
// 2
// 3
As long as the object implements the iterable interface it can be looped with the for of
loop. This includes arrays, maps and sets.
var map = new Map();
map.set('a', 1);
map.set('b', 2);
for (let pair of map) {
console.log(pair);
}
// [a,1]
// [b,2]
Arrays, sets and maps also expose the entries
, keys
and values
functions for returning specialised iterators. The keys
iterator loops over only the keys, the values
iterator only the values, and the entries
iterator the key/value pairs.
var map = new Map();
map.set('a', 1);
map.set('b', 2);
for (let key of map.keys()) {
console.log(key);
}
// a
// b
In ES6 strings also implement the iterable interface.
for (let char of 'foo') {
console.log(char);
}
// 'f'
// 'o'
// 'o'
Top comments (0)