闭包实现迭代器效果

迭代器

反复调用一个函数 会返回不同的值 但这些值有具有一定关联 比如是数组内顺序存储的数

  • 数组迭代器
var arr  = [1,2,3,4,5];
var next = (function(){
var index = 0;
return function(){
	if(index>=arr.length){
		throw new Error("无法继续迭代");
	}
	return arr[index++];
}
})()

next();//1
1
next();
2
next();
3
next();
4
next();
5
next();
VM871:6 Uncaught Error: 无法继续迭代
    at <anonymous>:6:9
    at <anonymous>:1:1

猜你喜欢

转载自blog.csdn.net/weixin_42043407/article/details/121406263