迭代器:帮助我们遍历某个数据结构的一个对象
前提:一个对象,符合迭代器协议-产生一系列值的标准方式(next函数)
next函数无参数或者一个参数,且会返回一个有done和value属性的对象
当迭代器有值的时候done为false,超出迭代长度的时候为true
value为当前迭代的值,超出迭代长度值为undefined 此时done为true
const name = ["abc","def","hij"]
let index = 0
const nameiterator = { //一个对象
next(){ //迭代器协议
if(index < name.length){
return { done:false,value:name[index++] }
}else{
return { done:true,value:undefined }
}
}
}
console.log(nameiterator.next());
console.log(nameiterator.next());
console.log(nameiterator.next());
console.log(nameiterator.next());
可迭代对象:符合可迭代协议(实现[Symbol.iterator]函数:返回值为一个迭代器)
// 可迭代对象
const objIterator = {
name: ["abc","def","hij"],
[Symbol.iterator]:function(){ //可迭代协议
let index = 0
return {
next:()=>{
if(index < this.name.length){ //根据done为false返回值
return { done:false,value:this.name[index++] }
}else{
return { done:true,value:undefined }
}
}
}
}
}
// 可迭代对象应用:for...of 展开运算符
for(let item of objIterator){
console.log('item: ', item);
}
//展开运算符
const arr = [1,2,3]
const newArr = [...arr,...objIterator]
console.log('newArr: ', newArr);
// 解构赋值
const [a,b] = objIterator
console.log('a: ', a);
console.log('b: ', b);
// 创建一些其他对象
const set = new Set(objIterator) // new Set() 传进的就是一个可迭代对象
console.log('set: ', set);
const arr1 = Array.from(objIterator) // 将可迭代对象转为数组,可用于arguments
console.log('arr1: ', arr1);
// Promise.all方法
Promise.all(objIterator).then(res=>{ //要求传入的也是个可迭代对象
console.log('res: ', res);
})
自定义类的可迭代性,迭代器还有return属性,监听迭代终止
//自定义类的可迭代性
class Classroom{
constructor(address,name,students){
this.address = address
this.name = name
this.students = students
}
entry(name){
this.students.push(name)
}
[Symbol.iterator](){
let index = 0
return {
next:()=>{
if(index < this.students.length){
return { done:false,value:this.students[index++] }
}else{
return { done:true,value:undefined }
}
},
return:()=>{ //监听迭代的终止操作,无参数,了解即可,
console.log("迭代被终止了");
return { done:true,value:undefined }
}
}
}
}
const classroom = new Classroom("综合楼一楼","103号教室",["张三","李斯","王五"])
classroom.entry("老六")
console.log('classroom: ', classroom);
for(let item of classroom){
if(item == "王五") break;
console.log('item: ', item);
}