简体   繁体   中英

Making plain objects iterable.(javascript)

So I'm working on a personal project after covering the first seven chapters of eloquent javascript by Marjin Heverbeke. Im creating school data handling system. So i already made my data structure which includes a lot of objects, so I created a test object to so that i could practice the iteration protocol, this is what i wrote

let object = {a:'a',b:'b',c:'c',d:'d',e:'e'};
object[Symbol.iterator]=function(){
    let keys = Object.keys(this);
    let count=0;
return {
    next(){
        if(count>keys.length){
            return {value: null, done:true};
        }
        else{
            let value=this[keys[count]];
            count++;
            return {value, done:false};
        }
    }
}
}

but when i do this

    for(let each of object){
       console.log([each]);
}

it outputs

//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]
//Array[undefined]

I don't know what is wrong oo, pls help.

Try this:

let object = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd',
  e: 'e',
};
object[Symbol.iterator] = function () {
  let keys = Object.keys(this);
  let count = 0;
  return {
    next() {
      if (count === keys.length) {
        return {
          value: null,
          done: true,
        };
      }
      let value = keys[count];
      count++;
      return {
        value,
        done: false,
      };
    },
  };
};

for (let each of object) {
  console.log([each]);
}

Note the errors were: let value=this[keys[count]]; and if (count > keys.length)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM