Object is not being produced on calling [Symbol.iterator]()

谁说胖子不能爱 提交于 2019-12-11 10:16:13

问题


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);


来源:https://stackoverflow.com/questions/47725541/object-is-not-being-produced-on-calling-symbol-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!