迭代器:一个特殊的对象,它包含一个next方法,next方法返回一个对象,这个对象包含两个属性,一个是value,表示成员的值,一个是done,done的值是一个布尔类型,表示迭代器是否结束。
方法1:基于es6手动创建一个迭代器:
const obj = {a: 'a', b: 'b', c: 'c'} obj[Symbol.iterator] = function() { const self = this const keys = Object.keys(self) const len = keys.length let pointer = 0 return { next() { const done = pointer >= len const value = !done ? self[keys[pointer++]] : undefined return { value, done } } } }
方法2: 基于es6 生成器(Generator): 调用 创建一个迭代对象。
let creatiterators=function *(a) { if(a==1){ yield "over" }else{ a=1 yield a+2; yield a+4 yield {a:a} } } let liststream=creatiterators() for (const val of liststream) { console.log(val) }