迭代器(lterator)是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署lterator接口,就可以完成遍历操作。
ES6创造了一种新的遍历命令for...of循环,lterator接口主要供for...of消费
原生具备iterator接口的数据(可用for of遍历)
a) Array
b) Arguments
c) Set
d) Map
e) String
f) TypedArray
g) NodeList
工作原理
a) 创建一个指针对象,指向当前数据结构的起始位置
b) 第一次调用对象的next方法,指针自动指向数据结构的第一个成员
c) 接下来不断调用next方法,指针一直往后移动,直到指向最后一个成员
d) 每调用next方法返回一个包含value和done属性的对象
注意:需要自定义遍历数据的时候,要想到迭代器
//声明一个数组
const xiyou = [‘唐僧‘,‘孙悟空‘,‘猪八戒‘,‘沙僧‘];
//使用 for...of遍历数组
for(let v of xiyou){
console.log(v);
}
let iterator = xiyou[Symbol.iterator]();
console.log(iterator);
//调用对象的next方法
console.log(iterator.next());//{value:‘唐僧‘,done:false}
console.log(iterator.next());//{value:‘孙悟空‘,done:false}
console.log(iterator.next());//{value:‘猪八戒‘,done:false}
console.log(iterator.next());//{value:‘沙僧‘,done:false}
console.log(iterator.next());//{value:undefined,done:true}
//声明一个对象
const banji = {
name:‘终极一班‘,
stus:[
‘xiaoming‘,
‘xiaojia‘,
‘xiaochen‘,
‘xiaowang‘,
],
[Symbol.iterator](){
//索引变量
let index = 0;
return {
next:() => {
if(index < this.stus.length){
return {value:this.stus[i],done:false};
//下标自增
index++;
//返回结果
return result;
}else{
return {value:undefined,done:true};
}
}
};
}
}
//遍历这个对象
for(let v of banji){
console.log(v);
//xiaoming
//xiaojia
//xiaochen
//xiaowang
}
// banji.stus.forEach();//
原文:https://www.cnblogs.com/AaronNotes/p/14364219.html