JS版设计模式--Iterator
来源:互联网 发布:20 sim软件下载 编辑:程序博客网 时间:2024/06/05 02:42
迭代模式(Iterator)
var Iterator = function () { var data = [1,2,3,4,5], index = 0, length = data.length; return { hasNext: function () { return index < length; }, next: function () { var element = data[index]; index += 1; return element; }, rewind: function () { index = 0; return true; }, current: function () { return data[index < length ? index : length - 1]; } } } var it = Iterator(); while (it.hasNext()) { console.log(it.next()); // 1,2,3,4,5 } it.rewind(); console.log(it.current()); // 1
顺便一提
我们经常会用for循环遍历数组 var arr = [1,2,3,4,5], i, max; for(i = 0, max = arr.length; i < max; i++) { if(i === 2) { // 在for循环中可以使用break或者continue } console.log(arr[i]); } ES5中又加入了 forEach(function (value, item, array) {}); 在这个里面就不可以用break了。 可能有些同学会用forin 来遍历数组。千万不要那样做: 1、得到的index类型为string,如果你要对index进行计算就可能出错。 2、可能会遍历原型链上的属性(要使用hasOwnProperty()) 3、顺序可能被改变。
0 0
- JS版设计模式--Iterator
- JS-Javascript 迭代器设计模式 Iterator pattern
- 设计模式--Iterator模式
- 设计模式---Iterator模式
- 设计模式--Iterator 模式
- 【设计模式】Iterator模式
- 设计模式之Iterator
- Iterator设计模式
- Iterator设计模式
- 设计模式之Iterator
- 设计模式之 iterator
- 设计模式 -- Iterator(迭代器)
- Iterator设计模式
- Iterator设计模式
- Iterator------设计模式
- 设计模式 Iterator
- 设计模式之Iterator
- 设计模式Iterator
- 51nod 1035最长循环节
- 使用logback时,出现Maven SLF4J: Class path contains multiple SLF4J bindings
- 【NOIP2010】洛谷1199 三国游戏
- win10vc6.0不能正常使用的解决问题
- hdoj5968-异或密码
- JS版设计模式--Iterator
- 初始化ArrayList、List的两种方法
- git操作手册
- JavaScript欺骗词法的eval、with与catch及其性能问题
- java数据结构队列(Queue)之个人理解
- K一最邻近算法在文本自动分类中的应用
- 数据挖掘岗面试总结(转载)
- Apache服务器搭建及开启
- web开发JS学习(二)关于document.write会覆盖文档流的理解