再次学习 Iterator 迭代器 与 Generator 生成器
2024-09-08 07:17:33
Iterator :
返回的结果是:{value, done}
function chef(foods){
let i = 0;
return {
next(){
let done = ( i> foods.length);
let value = !done? foods[i++]:undefined
return{
value,
done
}
}
}
}
let wanghao = chef(['西红柿','鸡蛋'])
console.log(wanghao.next());
console.log(wanghao.next());
...
generator(生成器):
function* chef()
{
yeild '西红柿';
yeild '鸡蛋';
}
let wanghao = chef();
改造下:
function* chef(foods){
for(var i =0;i<foods.length;i++)
{
yeild foods[i]
}
}
var wanghao = chef(['西红柿','鸡蛋'])
console.log(wanghao.next());
console.log(wanghao.next());
...
用class生成的Iterator:
class chef {
constructor(arr) {
this.foods = arr
this.i = 0;
}
next() {
let done = (this.i >= this.foods.length)
let value = !done ? this.foods[this.i++] : undefined
return {
value,
done
}
}
}
var a = new chef([1, 2, 3]);
console.log(a.next());
console.log(a.next());
console.log(a.next());
console.log(a.next());
console.log(a.next());
最新文章
- unity导出工程导入到iOS原生工程中详细步骤
- android开发虚拟机不能正常启动
- supersr--NSURLSessionConfiguration-下载进度
- requirejs 小结
- Android视图SurfaceView的实现原理分析
- JavaScript toFixed() 方法
- C# ACM poj1007
- 简洁 Abstract Factory模式(3.1)
- Using GUID to generate the unique file name in C#
- ffmpeg常用参数一览
- ASP.NET MVC 学习之路-5
- Git远程仓库的使用(三)
- win10 uwp 使用 Geometry resources 在 xaml
- vue中$on与$emit的实际应用
- vmware上虚拟机:Network error: Connection refused 排查
- SAP事物代码
- linux tail -f messages查看控制台失败
- 关于component-scan中base-package包含通配符的问题探究
- SpringBoot入门(2)
- leetcode Ch1-Search
热门文章
- MAC中Parallels Desktop windows忘记密码的解决办法
- Qt之QImageWriter
- [Angular + TsLint] Disable directive selector tslint error
- E-UTRA channel bandwidths per operating band (36.101)
- django 笔记15 ajax系列
- Linux 设置交换分区
- 我所理解的monad(1):半群(semigroup)与幺半群(monoid)
- javascript实现多线程 Concurrent.Thread.js
- [USACO07MAR]每月的费用Monthly Expense
- 今日SGU 5.29