通过Symbol.iterator进行迭代不会发生

时间:2018-10-01 13:57:14

标签: javascript ecmascript-6

Node.js v10.11.0

为什么我的代码中不会发生迭代?

'use strict';
const stuff = Object.create(null)
stuff.items = ['a','b','c','d']
stuff[Symbol.iterator] = function*(){
    return this.items[Symbol.iterator]()
}
for(let n of stuff){
    console.log(n) // It doesn't happen
}

2 个答案:

答案 0 :(得分:1)

您的生成器函数不yield,您只返回另一个迭代器,但是在for..of中忽略了返回值。相反,您要么产生另一个迭代器的条目:

 stuff[Symbol.iterator] = function*(){
   yield* this.items[Symbol.iterator]();
 };

或者您将生成器功能转换为常规功能(删除*):

stuff[Symbol.iterator] = function() {
   return this.items[Symbol.iterator]();
};

答案 1 :(得分:1)

stuff迭代器设置为items迭代器:

const stuff = Object.create(null)

stuff.items = ['a','b','c','d']

stuff[Symbol.iterator] = stuff.items[Symbol.iterator].bind(stuff.items);

for(let n of stuff){
    console.log(n) // It doesn't happen
}