2

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.

0

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.