生成器替代迭代器的使用
生成器替代迭代器会让代码更加的简洁----主要是是运用 “yield 值”----对应于{done:false,value:值} 同时就可以借助遍历来让代码更加的简洁 具体看代码
yield*---表达式用于委托另一个generator或者可迭代对象
1 //1:生成器来替代迭代器 2 function* creatrArrIterator(arr) { 3 //4:第四种写法 4 // yield "tsf" //{done:false,value:"tsf"} 5 // yield "tyy" //{done:false,value:"tyy"} 6 // yield "zjj" //{done:false,value:"zjj"} 7 //3:第三种写法 后面跟上可迭代对象 8 yield* arr 9 //2:第二种写法 10 // for (const a of arr) { 11 // yield a 12 // } 13 //1:第一种写法 14 // return { 15 // next: function() { 16 // if (index < arr.length) { 17 // return { done: false, value: arr[index++] } 18 19 // } else { 20 // return { done: true, value: undefined } 21 22 // } 23 // } 24 // } 25 } 26 const names = ['tyy', "tsf", "zjj"] 27 const namesIterator = creatrArrIterator(names) 28 console.log(namesIterator.next()); 29 console.log(namesIterator.next()); 30 console.log(namesIterator.next()); 31 console.log(namesIterator.next()); 32 //2:创建一个函数,这个函数可以迭代一个范围内的数字 33 //10 20 34 function* createRangeIterator(start, end) { 35 let index = start 36 //1:第一种写法 37 // return { 38 // next: function() { 39 // if (index < end) { 40 // return { done: false, value: index++ } 41 // } else { 42 // return { done: true, value: undefined } 43 // } 44 // } 45 // } 46 while (index < end) { 47 yield index++ 48 49 } 50 } 51 const RangeIterator = createRangeIterator(10, 20) 52 console.log(RangeIterator.next()); 53 console.log(RangeIterator.next()); 54 console.log(RangeIterator.next()); 55 console.log(RangeIterator.next()); 56 console.log(RangeIterator.next()); 57 //3:ClassRoom案列 58 class Classroom { 59 constructor(address, name, students) { 60 this.address = address 61 this.name = name, 62 this.students = students 63 } 64 entry(newstudent) { 65 this.students.push(newstudent) 66 } 67 foo 68 //3:另一种语法 69 // *[Symbol.iterator]() { 70 // yield* this.students 71 // } 72 //2:第二种写法 73 [Symbol.iterator] = function*() { 74 yield* this.students 75 } 76 //1:第一种写法 77 // [Symbol.iterator]() { 78 // let index = 0 79 // return { 80 // next: () => { 81 // if (index < this.students.length) { 82 // return { done: false, value: this.students[index++] } 83 // } else { 84 // return { done: true, value: undefined } 85 // } 86 // }, 87 // } 88 // } 89 } 90 const calssroom = new Classroom("1栋", "实验楼", ['tyy', 'tsf']) 91 calssroom.entry('zjj') 92 for (const s of calssroom) { 93 console.log(s); 94 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现