Using Objects in For Of Loops

后端 未结 14 2073
春和景丽
春和景丽 2020-11-28 05:56

Why isn\'t is possible to use objects in for of loops? Or is this a browser bug? This code doesn\'t work in Chrome 42, saying undefined is not a function:

te         


        
14条回答
  •  半阙折子戏
    2020-11-28 06:24

    It is possible to define an iterator over any giving object, this way you can put different logic for each object

    var x = { a: 1, b: 2, c: 3 }
    x[Symbol.iterator] = function* (){
        yield 1;
        yield 'foo';
        yield 'last'
    }
    

    Then just directly iterate x

    for (let i in x){
        console.log(i);
    }
    //1
    //foo
    //last
    

    It is possible to do the same thing on the Object.prototype object And have a general iterator for all objects

    Object.prototype[Symbol.iterator] = function*() {
        for(let key of Object.keys(this)) {
             yield key 
        } 
     }
    

    then iterate your object like this

    var t = {a :'foo', b : 'bar'}
    for(let i of t){
        console.log(t[i]);
    }
    

    Or this way

    var it = t[Symbol.iterator](), p;
    while(p = it.next().value){
        console.log(t[p])
    }
    

提交回复
热议问题