Iterator

数组默认有迭代器属性

    var arr = [111,222,333];
    var aa = arr[Symbol.iterator]();
    aa.next(); // { value: 111, done: false }
    aa.next(); // { value: 222, done: false }
    aa.next(); // { value: 333, done: false }
    aa.next(); // { value: undefined, done: true }

可以用在 数组 Map Set 类数组

    var m = new Set([11,22,33]);//set类似于数组
    console.log(m);
    var qq=m[Symbol.iterator]();
    console.log(qq.next());//{value: 11, done: false}


    var s = new Map([['name','shi'],['age',3]]);
    s.set("sex",'nv')
    console.log(s);
    var i=s[Symbol.iterator]();
    console.log(i.next());

类数组

    var try=document.getElementsByName("div");
    console.log(try);

自定义遍历器

    var arr = [111,222,333];
    function aa(arr){
    var i=-1;
    function next(){
        i++;
        let value;
        let done=false;

        if (i==arr.length) {
            value=undefined;
            done=true;
        }else{
            value=arr[i];
        }
        return{value:value,done:done};
    }
    return {next:next};
}

    var zz=aa(arr); 
    console.log(zz.next());//Object {value: 111, done: false}
    console.log(zz.next());//Object {value: 222, done: false}
    console.log(zz.next());//Object {value: 333, done: false}
    console.log(zz.next());//Object {value: undefined, done: true}
posted @ 2017-07-18 21:17  CoCo5  阅读(161)  评论(0编辑  收藏  举报