Using Objects in For Of Loops

后端 未结 14 2061
春和景丽
春和景丽 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条回答
  •  萌比男神i
    2020-11-28 06:20

    Iterator, Iterable and for..of loop in ECMAScript 2015/ ES6

    let tempArray = [1,2,3,4,5];
    
    for(element of tempArray) {
      console.log(element);
    }
    
    // 1
    // 2
    // 3
    // 4
    // 5
    

    But if we do

    let tempObj = {a:1, b:2, c:3};
    
    for(element of tempObj) {
       console.log(element);
    }
    // error
    

    We get error because for..of loop works only on Iterables, that is, the object which has an @@iterator that adheres to Iterator protocol, meaning it must have an object with a next method. The next method takes no arguments and it should return an object with these two properties.

    done: signals that the sequence has ended when true, and false means there may be more values value: this is the current item in the sequence

    So, to make an object Iterable that is to make it work with for..of we can:

    1 .Make an object an Iterable by assigning to it’s mystical @@iterator property through the Symbol.iterator property.Here is how:

    let tempObj = {a:1, b:2, c:3};
    
    tempObj[Symbol.iterator]= () => ({
    next: function next () {
    return {
        done: Object.keys(this).length === 0,
        value: Object.keys(this).shift()
         }
        }
      })
    
    for(key in tempObj){
     console.log(key)
    }
    // a
    // b
    // c
    

    2.Use Object.entries, which returns an Iterable:

    let tempObj = {a:1, b:2, c:3};
    
    for(let [key, value] of Object.entries(tempObj)) {
        console.log(key, value);
    }
    // a 1
    // b 2
    // c 3
    

    3.Use Object.keys, here is how:

    let tempObj = {a:1, b:2, c:3};
    for (let key of Object.keys(tempObj)) {
        console.log(key);
    }
    
    // a
    // b
    // c
    

    Hope this helps!!!!!!

提交回复
热议问题