Object is not being produced on calling [Symbol.it

2019-07-24 19:11发布

问题:

This is this source code:

const james = {
    name: 'James',
    height: `5'10"`,
    weight: 185,
    [Symbol.iterator]:function*(){
    yield Object.keys(this) ;   
    }
};
const iterator = james[Symbol.iterator]();
//
console.log(iterator.next().value); // 'James'
console.log(iterator.next().value); // `5'10`
console.log(iterator.next().value); // 185

The first call to iterator.next().value is supposed to print

{"value":"James","key":"name","done":false}

but it is printing {"value":["name","height","weight"],"done":false}. How to resolve this?

回答1:

You yield all keys at once. Means that your first next do all work. All you need is to iterate over the keys and yield them in sequence.

const james = {
    name: 'James',
    height: `5'10"`,
    weight: 185,
    [Symbol.iterator]:function*(){   
       for(let key of Object.keys(this)) {
          yield  { propValue: this[key], propName: key};       
       }       
    }
};

const iterator = james[Symbol.iterator]();

console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());



回答2:

Actually, this would be the solution you are looking for, it outputs exactly what you need it to output.

const james = {
  name: 'James',
  height: `5'10"`,
  weight: 185,
  [Symbol.iterator]: function() {
    let keys = Object.keys(this), index = 0;
    return {
      next: () => { 
        return {
          key: keys[index], value: this[keys[index]], done: ++index >= keys.length 
        };  
      }
    }
  }
}

const iterator = james[Symbol.iterator]();

console.log(iterator.next().value);
console.log(iterator.next().value);
console.log(iterator.next().value);