迭代器是一种接口,为各种不同的数据结构提供统一的访问机制,任何数据结构只要部署Iterator接口,就可以完成遍历操作。
1.es6新增遍历 for....of,Iterator为其提供了实现基础
<script>
let arr = ["a","b","v","d"];
for(let i in arr) console.log(i);//0 1 2 3
for(let j of arr) console.log(j);// a b v d
//两者的区别在于,for...in 遍历的是key值; for...of遍历的value
</script>
2.原生具备iterator接口的数据(可用for...of遍历)
eg: array、set、map、arguments、string....
3.iterator工作原理
(1) 创建一个指针对象,指向当前数据结构的起始位置
(2) 第一次调用对象的next方法,指针自动指向数据结构的第一个成员
(3)通过不断调用next方法,指针一直向后移动,直到指向最后一个成员
(4) 没调用next方法返回一个包含value和done属性的对象,当value为undefined,done为true的时候结束
<script>
let arr = ["a", "b","c","d"]
let iterator = arr[Symbol.iterator]();
console.log(iterator.next());//{value: 'a', done: false}
console.log(iterator.next());//{value: 'b', done: false}
console.log(iterator.next());//{value: 'c', done: false}
console.log(iterator.next());//{value: 'd', done: false}
console.log(iterator.next());//{value: undefined, done: true}
</script>
手写实现iterator
<script>
let obj = {
name:"zhangsan",
age: 18,
habit: ["song","listen","read","write"]
}
//for(let j of obj){//Uncaught TypeError: obj is not iterable
//}
for(let i in obj)
console.log( obj[i] );// zhangsan 18 ['song', 'listen', 'read', 'write']
</script>
<script>
let obj = {
name:"zhangsan",
age: 18,
habit: ["song","listen","read","write"],
[Symbol.iterator](){
let index = 0;
return {
next:()=>{
if(index < this.habit.length)
return {value: this.habit[index++],done:false}
else
return {value: undefined, done:true}
}
}
}
}
for(let j of obj){
console.log(j)
}
</script>