Using Objects in For Of Loops

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

    If you are storing data in a key-value store, please use Map which is explicitly designed for this purpose.

    If you have to use an object though, ES2017 (ES8) allows you to use Object.values:

    const foo = { a: 'foo', z: 'bar', m: 'baz' };
    for (let value of Object.values(foo)) {
        console.log(value);
    }
    

    If that isn't supported yet, use a polyfill: Alternative version for Object.values()

    And finally if you're supporting an older environment that don't support this syntax, you'll have to resort to using forEach and Object.keys:

    var obj = { a: 'foo', z: 'bar', m: 'baz' };
    Object.keys(obj).forEach(function (prop) {
        var value = obj[prop];
        console.log(value);
    });
    

提交回复
热议问题