for... of
for ... of 문은 반복 가능한 객체 (내장 String, Array, 예를 들어 Array와 유사한 인수 또는 NodeList 객체, TypedArray, Map 및 Set 및 user-defined iterables 포함)를 반복하는 루프를 만들고,
객체의 각 고유한 속성값에 대해 실행될 명령문을 사용하여 custom 반복 후크를 호출합니다.
for (variable of iterable) {
statement
}
Iterating over an Array
let iterable = [10, 20, 30];
for (let value of iterable) {
value += 1;
console.log(value);
}
// 11
// 21
// 31
You can use const
instead of let
too, if you don't reassign the variable inside the block.let iterable = [10, 20, 30];
for (const value of iterable) {
console.log(value);
}
// 10
// 20
// 30
Iterating over a String
let iterable = 'boo';
for (let value of iterable) {
console.log(value);
}
// "b"
// "o"
// "o"
Iterating over a TypedArray
let iterable = new Uint8Array([0x00, 0xff]);
for (let value of iterable) {
console.log(value);
}
// 0
// 255
Iterating over a Map
let iterable = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let entry of iterable) {
console.log(entry);
}
// ['a', 1]
// ['b', 2]
// ['c', 3]
for (let [key, value] of iterable) {
console.log(value);
}
// 1
// 2
// 3
Iterating over a Set
let iterable = new Set([1, 1, 2, 2, 3, 3]);
for (let value of iterable) {
console.log(value);
}
// 1
// 2
// 3
Iterating over the arguments object
(function() {
for (let argument of arguments) {
console.log(argument);
}
})(1, 2, 3);
// 1
// 2
// 3
Iterating over a DOM collection
Iterating over DOM collections like NodeList
: 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');
}
Closing iterators
In for...of
loops, abrupt iteration termination can be caused by break
, continue
, throw
or return
. In these cases, the iterator is closed.
function* foo(){
yield 1;
yield 2;
yield 3;
};
for (let o of foo()) {
console.log(o);
break; // closes iterator, triggers return
}
Iterating over generators
function* fibonacci() { // a generator function
let [prev, curr] = [0, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
for (let n of fibonacci()) {
console.log(n);
// truncate the sequence at 1000
if (n >= 1000) {
break;
}
}
Iterating over other iterable objects
You can also iterate over an object that explicitly implements iterable protocol:
var iterable = {
[Symbol.iterator]() {
return {
i: 0,
next() {
if (this.i < 3) {
return { value: this.i++, done: false };
}
return { value: undefined, done: true };
}
};
}
};
for (var value of iterable) {
console.log(value);
}
// 0
// 1
// 2