How to make an iterator out of an ES6 class

后端 未结 6 1158
挽巷
挽巷 2021-01-30 10:21

How would I make an iterator out of an ES6 class in the same manner as JS1.7 SomeClass.prototype.__iterator__ = function() {...} syntax?

[EDIT 16:00]

<
6条回答
  •  一向
    一向 (楼主)
    2021-01-30 10:53

    Here's an example for iterating over a 2d matrix custom class in ES6

    class Matrix {
        constructor() {
            this.matrix = [[1, 2, 9],
                           [5, 3, 8],
                           [4, 6, 7]];
        }
    
        *[Symbol.iterator]() {
            for (let row of this.matrix) {
                for (let cell of row) {
                    yield cell;
                }
            }
        }
    }
    

    The usage of such a class would be

    let matrix = new Matrix();
    
    for (let cell of matrix) {
        console.log(cell)
    }
    

    Which would output

    1
    2
    9
    5
    3
    8
    4
    6
    7
    

提交回复
热议问题