写一个小的迭代器

在 JavaScript 中定义 一个迭代器对象,它提供了一个next() 方法,用来返回序列中的下一项。迭代器一旦被创建,就可以反复调用next()。

function Iterator(arr) {
        var index = 0;
        return {
            next: function () {
                if (index < arr.length) {
                    return arr[index++];
                } else {
                    index = 0;
                    return arr[0];
                }
            }
        }
    }
    var it = makeIterator(['a', 'b']);
    console.log(it.next());//a
    console.log(it.next());//b
    console.log(it.next());//a
    console.log(it.next());//a
    console.log(it.next());//b

猜你喜欢

转载自blog.csdn.net/JohnWakeman20/article/details/88313795