码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] Create a Custom Iterator for Any Array

时间:2019-12-28 13:31:41      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:bsp   hat   using   sed   const   ide   sso   read   ret   

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

标签:bsp   hat   using   sed   const   ide   sso   read   ret   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!