Skip to content
On this page

迭代

  • 迭代器(iterator)
    • for...in...:循环index值
    • for...of...:循环value值
javascript
let obj = {
	a:1,
	b:2,
	c:3
};
obj[Symbol.iterator] = function(){
	//迭代协议
	let keys = Object.keys(obj);
	let index = 0;
	return {
		next(){
			if(index >= keys.length){
				return {
					done:true //done代表循环是否完成,true表示已完成,false表示未完成
				}
			}
			else{
				return {
					done:false,
					value:{   //循环过程中的值
						key:keys[index],
						value:Object[keys[index++]]
					} 
				}
			}
		}
	}
};
for(ley val of obj){
	console.log(val)
}
  • Generator
javascript
funtion*fn(){
	yield 1;
	yield 2;
	yield 3;
}
let f = fn()
for(let val of f){}
javascript
funtion*fn(){
	yield new Promise((resolve,reject)=>{
		setTimeout(()=>{
			console.log("a");
			resolve();
		},500)
	});
	yield new Promise((resolve,reject)=>{
		setTimeout(()=>{
			console.log("b");
			resolve();
		},500)
	});
	yield new Promise((resolve,reject)=>{
		setTimeout(()=>{
			console.log("c");
			resolve();
		},500)
	}); 
}
function co(fn){
	let  f = fn()
	next()
	function next(data){
		let result = f.next()
		if(!result.done){
			//上一个异步走完,再执行下一个异步
			result.value.then((info)=>{
					console.log(info,data)
					next(info) 
			})
		}
	}
}

MIT Licensed | Copyright © 2021 - 2022