JavaScript设计模式之迭代器模式

2019-01-19  本文已影响0人  w候人兮猗

介绍

实例

    <p>jq each</p>
    <p>jq each</p>
    <p>jq each</p>
    var arr = [1,2,3]
    var nodeList = document.getElementsByTagName('p')
    var $p = $('p')

    arr.forEach(function (item) {
        console.log(item);
    })

    var i , length = nodeList.length
    for (i = 0;i<length;i++){
        console.log(nodeList[i]);
    }

    $p.each(function (key,p) {
        console.log(key,p)
    })
     //定义一个each 方法
    function each(data) {
        var $data = $(data) //生成迭代器
        $data.each(function (key,val) {
            console.log(key,val)
        })
    }
    
    each(arr)
    each(nodeList)
    each($p)

UML类图

image

代码演示

    class Container {
        constructor(list) {
            this.list = list
        }

        //生成遍历器
        getInterator() {
            return new Iterator(this.list)
        }
    }

    class Iterator {
        constructor(container) {
            this.list = container.list
            this.index = 0
        }

        next() {
            if (this.hasNext()) {
                return this.list[this.index++]
            }
            return null
        }

        hasNext() {
            if (this.index >= this.list.length) {
                return false
            }
            return true
        }
    }

    //test
    let arr = [1,2,3,4,5]
    let container = new Container(arr)
    let iterator = container.getInterator()
    while (iterator.hasNext()) {
        console.log(iterator.next())
    }

场景

ES6 Iterator

     //首先 返回[Symbol.Iterator]
    function each(data) {
        let iterator = data[Symbol.iterator]()
        // console.log(iterator.next())
        // console.log(iterator.next())
        // console.log(iterator.next())
        // console.log(iterator.next())
        let item = {done:false}
        while (!item.done){
            item = iterator.next()
            if(!item.done){
                console.log(item.value)
            }
        }
    }
    let arr = [1,2,3,4]
    // let nodeList = document.getElementsByTagName('a')
    let m = new Map()
    m.set('a',100)
    m.set('b',100)
    m.set('c',100)

    each(arr)
    // each(nodeList)
    each(m)
    
    //console
    
image
    function each2 (data){
        for (let item of data){
            console.log(item)
        }
    }
    
     each2(arr)
    // each(nodeList)
    each2(m)
    
image

ES6 Iterator与Generator

代码

https://github.com/ahwgs/design-pattern-learning/tree/master/10.JavaScript%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F%E4%B9%8B%E8%BF%AD%E4%BB%A3%E5%99%A8%E6%A8%A1%E5%BC%8F

原文

https://www.ahwgs.cn/javascriptshejimoshizhidiedaiqimoshi.html

上一篇下一篇

猜你喜欢

热点阅读