ES6+ 迭代器的实现原理

迭代器的原理

const arr = [1,2]
    function makeIterator(array){
        let nextIndex = 0;
        return {
            next:function(){
                return nextIndex < array.length ? {
                    value:array[nextIndex++],  //取值
                    done:false  //标记是否遍历完成
                } :{
                    value:undefined,
                    done:true
                }
            }
        }
    }
    let res = makeIterator(arr)
    console.log(res.next());
    console.log(res.next());
    console.log(res.next());
    console.log(res.next());

迭代器的使用

let arr1 = [1,2,3,4,5]
    let iter = arr1[Symbol.iterator]()
    console.log(iter.next());
    console.log(iter.next());
    console.log(iter.next());
    console.log(iter.next());
    console.log(iter.next());
    console.log(iter.next());
    console.log(iter.next());
    console.log(iter.next());
    console.log(iter.next());

对象实现可迭代

et obj = {
        data:[1,2,3,4],
        [Symbol.iterator](){
            let index = 0
            let that = this
            return {
                next(){
                    if(index<that.data.length){
                        return {
                            value:that.data[index++],
                            done:false
                        }
                    }else{
                        return {
                            value:undefined,
                            done:true
                        }
                    }
                }
            }
        }
    }

    for (let i of obj ){
        console.log(i);
    }
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页