数组迭代
class Iterator{ constructor(assemble) { let self = this; self.assemble = assemble; self.index = 0 } next() { let self = this, assemble = self.assemble; if (self.index > assemble.length - 1) { return { done: true, value:undefined } } return { done: false, value:this.assemble[self.index++] } }} let itor = new Iterator([10, 30, 20, 40]) console.log(itor.next()); console.log(itor.next()); console.log(itor.next()) console.log(itor.next()) console.log(itor.next()) 对象迭代 let obj = { name: 'zhufeng', age: 12, teacher:'team' } //obj[Symbol.iterator] Object.prototype[Symbol.iterator] = function () { let assemble = this, keys = Object.keys(assemble).concat(Object.getOwnPropertySymbols(assemble)), index = 0; return { next() { if (index > keys.length - 1) { return { done: true, value: undefined }; } return { done: false, value:assemble[keys[index++]] } } } } for (let value of obj) { console.log(value) 浏览器展示如下: } 对象迭代: let obj = { name: 'zhufeng', age: 12, teacher:'team' } //obj[Symbol.iterator] 可以给对象添加属性[Symbol.iterator]也可以给对象原型添加属性[Symbol.iterator] Object.prototype[Symbol.iterator] = function () { let assemble = this, keys = Object.keys(assemble).concat(Object.getOwnPropertySymbols(assemble)), index = 0; return { next() { if (index > keys.length - 1) { return { done: true, value: undefined }; } return { done: false, value:assemble[keys[index++]] } } } } for (let value of obj) { console.log(value) } 浏览器输出: