Technology Sharing

ES6 Iterator and for...of loop (V)

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Iterator features:

  • Unified interface: Whether it is an array, string or custom object, as long as they have a default iterator, they can be traversed using the for...of loop.
  • Iterable objects: Objects with the [Symbol.iterator] attribute are considered iterable. [Symbol.iterator] is a method that returns an iterator.
  • Iterator object: An iterator is an object with a next() method that returns an object containing value and done properties. value is the value of the current iteration, and done is a Boolean value indicating whether the iteration is completed.

for…of loop features:

  • Concise syntax: Use for...of to iterate over each element in an iterable object without writing additional iteration logic.
  • Automatic iteration: The for...of loop automatically calls the iterator's next() method to get the next value.
  • Exception handling: You can use try...catch in a for...of loop to catch exceptions thrown during the iteration process.

1: Use for...of to iterate over an array

let numbers = [1, 2, 3, 4, 5];

for (let number of numbers) {
    console.log(number); // 依次输出 1 到 5
}
  • 1
  • 2
  • 3
  • 4
  • 5

2: Use for...of to iterate over a string

let str = "Hello";

for (let char of str) {
    console.log(char); // 依次输出 'H', 'e', 'l', 'l', 'o'
}
  • 1
  • 2
  • 3
  • 4
  • 5

3: Custom iterator

let myIterable = {
    [Symbol.iterator]: function* () {
        yield 1;
        yield 2;
        yield 3;
    }
};

for (let value of myIterable) {
    console.log(value); // 依次输出 1, 2, 3
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

4: Use for...of with custom iterators

function* numberIterator(max) {
    let current = 1;
    while (current <= max) {
        yield current++;
    }
}

for (let number of numberIterator(5)) {
    console.log(number); // 依次输出 1 到 5
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

5: Use for...of to catch exceptions

let iterable = [1, 2, 3, 4, 'error', 6];

for (let item of iterable) {
    try {
        if (typeof item === 'string') {
            throw new Error('Invalid value');
        }
        console.log(item * 2); // 依次输出 2, 4, 6, 8
    } catch (e) {
        console.error(e.message); // 输出:Invalid value
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

6: Use Array.from to convert iterable objects into arrays

let str = "Iterator";

let arrayFromIterable = Array.from(str);
console.log(arrayFromIterable); // 输出:['I', 't', 'e', 'r', 'a', 't', 'o', 'r']
  • 1
  • 2
  • 3
  • 4

Notice

compatibility: The for…of loop is supported in modern browsers and Node.js, but may not be supported in some older JavaScript environments.
performance: For large collections, a for...of loop may not be as efficient as a traditional for loop because each iteration requires calling the iterator's next() method.

7: Symbol.iterator for arrays

let arr = [1, 2, 3];

// 数组是可迭代对象,具有默认的 Symbol.iterator 属性
let iterator = arr[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: undefined, done: true }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

8: Symbol.iterator for strings

let str = "abc";

// 字符串也是可迭代对象
let strIterator = str[Symbol.iterator]();

console.log(strIterator.next()); // { value: "a", done: false }
console.log(strIterator.next()); // { value: "b", done: false }
console.log(strIterator.next()); // { value: "c", done: false }
console.log(strIterator.next()); // { value: undefined, done: true }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

9: Manually using Symbol.iterator

let myObj = {
    items: [3, 5, 7],
    [Symbol.iterator]: function* () {
        for (let item of this.items) {
            yield item * 2; // 迭代器返回值的两倍
        }
    }
};

let iterator = myObj[Symbol.iterator]();

console.log(iterator.next()); // { value: 6, done: false }
console.log(iterator.next()); // { value: 10, done: false }
console.log(iterator.next()); // { value: 14, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15