Using Objects in For Of Loops

后端 未结 14 2003
春和景丽
春和景丽 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:26

    Because object literal does not have the Symbol.iterator property. To be specific, you can only iterate over String, Array, Map, Set, arguments, NodeList(not widely support) and Generator with for...of loop.

    To deal with Object Literal iteration, you have two options.

    for...in

    for(let key in obj){
        console.log(obj[key]); 
    }
    

    Object.keys + forEach

    Object.keys(obj).forEach(function(key){
        console.log(obj[key]);
    });
    
    0 讨论(0)
  • 2020-11-28 06:30

    I made objects iterable with this code:

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

    Usage:

    for(let [ key, value ] of {}) { }
    

    Alternativly:

    for(let [ key, value ] of Object.entries({})) { }
    
    0 讨论(0)
提交回复
热议问题