자바스크립트 반복자(Iterator)

In JavaScript, an iterator is an object that provides a way to access elements in a collection one by one, allowing us to iterate over data structures like arrays, strings, maps, and sets. It provides a standardized iteration protocol and follows the iterable protocol.

The iterable protocol defines a method called Symbol.iterator, which is used to create an iterator object. This iterator object should have a next() method that returns the next element in the collection along with a boolean value to indicate if there are more elements left.

To understand iterators better, let’s look at an example of how to create and use an iterator in JavaScript:

const myArray = [1, 2, 3, 4, 5];

const iterator = myArray[Symbol.iterator]();

console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: 4, done: false }
console.log(iterator.next()); // { value: 5, done: false }
console.log(iterator.next()); // { value: undefined, done: true }

In the code snippet above, we create an array myArray and obtain an iterator by using the Symbol.iterator method. We then use the next() method to iterate over the array and print the values. Each call to next() returns an object with a value property that represents the next element in the array and a done property that indicates if there are more elements left to iterate.

The done property will be false until all elements have been iterated. After the last element, done will be true and value will be undefined.

Iterators provide a simple yet powerful way to iterate over collections in JavaScript. They can be used in loops, such as for...of loops, and can also be manually controlled using the next() method.

Using iterators allows for more efficient memory usage, as you can process elements on the fly without the need to store the entire collection in memory.

In conclusion, understanding and utilizing iterators in JavaScript can greatly enhance your ability to work with collections and efficiently process data. It is an important concept to grasp for any JavaScript developer.