首页 > 编程语言 > 详细

[Javascript] Create a Custom Iterator for Any Array

时间:2019-12-28 11:54:48      阅读:72      评论:0      收藏:0      [点我收藏+]

Using Symbol.iterator, you can create custom iterators that can be used inside of for loops and Array spreads. This lesson walks you through creating a function to create iterators from arrays that you pass into the function.

 

const abcs = ["A", "B", "C"]

const numbers = [1, 2, 3]

const createReverseIterator = array => ({
    [Symbol.iterator]() {
        let i = array.length
        return {
            next: () => ({
                value: array[--i],
                done: i < 0
            })
        }
    }
})


for (let value of createReverseIterator(numbers)) {
    console.log(value)
}

 

[Javascript] Create a Custom Iterator for Any Array

原文:https://www.cnblogs.com/Answer1215/p/12111188.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!