湖北城乡和建设官方网站,做壁纸网站,网页紧急升级恢复,营销策划与运营方案迭代器iterator
是一种 ES6 规范#xff0c;具有这种机制的数据结构才可以使用for of循环#xff1a;返回每一项的值#xff1b; 原型链具有Symbol.iterator属性的数据结构都具备#xff1b;如数组、部分类数组、字符串等#xff1b; 普通对象就不能用#xff1b;
for-…迭代器iterator
是一种 ES6 规范具有这种机制的数据结构才可以使用for of循环返回每一项的值 原型链具有Symbol.iterator属性的数据结构都具备如数组、部分类数组、字符串等 普通对象就不能用
for-of循环原理循环获取属性值
执行可迭代原型链上的Symbol.iterator方法该方法返回一个包含next方法的对象;通过循环执行next方法得到方法返回的对象根据对象中值抛出返回值
let obj {name: aa,age: 10,
}Object.prototype[Symbol.iterator] function iterator() {let self this,index -1,keys Reflect.ownKeys(self)console.log(keys) // [name, age]return {next() {indexif (index keys.length - 1) {return {done: true,value: undefined,}}return {done: false,value: self[keys[index]],}},}
}
for (const iterator of obj) {console.log(iterator) // aa 10
}