Iterator and for... of vs for... in

Keywords: Javascript

Iterator iterator (convenience)

Improving the efficiency of accessing data with traversal excuses

Equivalent to pointer (default is - 1);

Convenient excuses

There is the next method (next moves the current pointer to the next location and returns an object {value:,done:})

Arrays have iterator properties by default

    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 }

Can be used in arrays of Map Set class arrays

    var m = new Set([11,22,33]);//set is similar to an array
    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());

Class array

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

Custom Convenience

    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}
    

for..of vs for...in

Ordinary circulation convenience

var arr=[1,2,3,4,5,6];
for (var i = 0, l = arr.length; i<l; i++) {
    console.log(arr[i]);
};
arr.forEach(i=>{
    console.log(i);
})

Iterator convenience

var bb=arr[Symbol.iterator]();
var cc=bb.next();
while(!cc.done){
    console.log(cc.value);
    cc=bb.next();
}

for of array convenience

for(var item of arr){
    console.log(item);
} 

for of set convenience

var s=new Set(['a','b','c']);
for(var item  of s){
    console.log(item);
}

for in is used to facilitate objects

// 
var obj={
    x:1,y:2,z:3
}
for(var i in obj ){
    console.log(i)//x,y,z
    console.log(obj[i]);//x 1 y 2 z 3
}

Posted by Cheeky Chino on Thu, 14 Feb 2019 01:00:19 -0800