Using Objects in For Of Loops

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

    Object literals don't have built-in iterators, which are required to work with for...of loops. However, if you don't want to go thru the trouble of adding your own [Symbol.iterator] to your object, you can simply use the Object.keys() method. This method returns an Array object, which already has a built-in iterator, so you can use it with a for...of loop like this:

    const myObject = {
        country: "Canada",
        province: "Quebec",
        city: "Montreal"
    }
    
    for (let i of Object.keys(myObject)) {
        console.log("Key:", i, "| Value:", myObject[i]);
    }
    
    //Key: country | Value: Canada
    //Key: province | Value: Quebec
    //Key: city | Value: Montreal
    

提交回复
热议问题