生成器、迭代器
给对象添加迭代器属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| let obj = { a:1, b:2, c:3, [Symbol.iterator]: function(){ var index = 0; let map = new Map(); for(var key in this){ map.set(key, this[key]) } return { next(){ var mapEntries = [...map.entries()]; if(index < map.size){ return { value:mapEntries[index++], done:false } } return { value:undefined, done:true } } } } }
|
生成器函数
每次调用next函数时,只会执行到下一个yield,之后的代码不会执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| function* test(){ let value1 = yield 1; console.log(value1); let value2 = yield 2; console.log(value2); let value3 = yield 3; console.log(value3); let value4 = yield 4; console.log(value4); } var iter = test();
console.log(iter.next('one')); console.log(iter.next('two')); console.log(iter.next('three')); console.log(iter.next('four')); console.log(iter.next());
|
使用生成器函数编写迭代器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| var obj = { a:1, b:2, c:3, [Symbol.iterator]: function* () { var index = 0; let map = new Map(); for(var key in this){ map.set(key, this[key]) } var mapEntries = [...map.entries()]; while(index < mapEntries.length){ yield mapEntries[index++]; } } } for (var i of obj) { console.log(i); }
|