Using Objects in For Of Loops

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

    in ES6 you could go with generator:

    var obj = {1: 'a', 2: 'b'};
    
    function* entries(obj) {
      for (let key of Object.keys(obj)) {
        yield [key, obj[key]];
      }
    }
    
    let generator = entries(obj);
    
    let step1 = generator.next();
    let step2 = generator.next();
    let step3 = generator.next();
    
    console.log(JSON.stringify(step1)); // {"value":["1","a"],"done":false}
    console.log(JSON.stringify(step2)); // {"value":["2","b"],"done":false}
    console.log(JSON.stringify(step3)); // {"done":true}
    

    Here is the jsfiddle. In the output you will get an object with the "value" and "done" keys. "Value" contains everything you want it to have and "done" is current state of the iteration in bool.

提交回复
热议问题