JavaScript实现Iterator模式实例分析

经常在网上看到有不少JS设计模式的示例。这里写一下JavaScript实现Iterator模式的方法,记录在此,仅作备忘:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta content="text/html; charset=utf-8" http-equiv="Content-Type" /> <title>无标题 1</title> </head> <body> <script type="text/javascript" language="javascript"> ///@定义一个迭代器对象 function Iterator(arr) { this.obj=arr; this.length=this.obj.length; this.index=0; //从前往后 } Iterator.prototype= { current:function() { return this.obj[this.index-1]; }, first:function() { return this.obj[0]; }, last:function() { return this.obj[this.length-1]; }, hasNext:function() { this.index=this.index+1; if(this.index>this.length || null==this.obj[this.index-1]) return false; return true; } } Array.prototype.createIterator=function() { return new Iterator(this); } var test=['abc1','abc2','abc3']; var iter=test.createIterator(); while(iter.hasNext()) { var tempArr=iter.current(); alert(tempArr); } </script> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgdpgw.html