国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

學習JavaScript設計模式之迭代器模式

2019-11-20 10:45:43
字體:
來源:轉載
供稿:網友
  • 迭代器模式是指提供一種方法順序訪問一個聚合對象中的各個元素,而又不需要暴露該對象的內部表示。

JavaScript中的Array.prototype.forEach

一、jQuery中的迭代器

$.each([1, 2, 3], function(i, n) {  console.log("當前下標為:"+ i + " 當前元素為:"+ n );});

二、實現自己的迭代器

var each = function(ary, callback) {  for(var i = 0, l = ary.length; i < l; i++) {    callback.call(ary[i], i, ary[i]);  }  };each([1, 2, 3], function(i, n) {  console.log("當前下標為:"+ i + " 當前元素為:"+ n );});

注意:區別于Array.prototype.forEach的參數!!!

[1, 2, 3].forEach(function(n, i, curAry){  console.log("當前下標為:"+ i + " 當前元素為:"+ n + " 當前數組為:" + curAry);})

三、內部迭代器、外部迭代器

(1)內部迭代器:已經定義好了迭代規則,它完全接手整個迭代過程,外部只需一次初始調用。上述自定義each即為內部迭代器!
(2)外部迭代器:必須顯示地請求迭代下一個元素。
示例:判斷兩個數組是否相等

示例一:內部迭代器

// 內部迭代器var each = function(ary, callback) {  for(var i = 0, l = ary.length; i < l; i++) {    callback.call(ary[i], i, ary[i]);  }  };// 比較函數var compareAry = function(ary1, ary2) {  if(ary1.length != ary2.length) {    throw new Error("不相等"); // return console.log("不相等");   }  // 且住  each(ary1, function(i, n) {    if(n !== ary2[i]) {      // return console.log("不相等");       // return 只能返回到each方法外,后續console.log("相等")會繼續執行,所以這里得使用throw      throw new Error("不相等");    }  });  console.log("相等");}compareAry([1, 2, 3], [1, 2, 4]);

示例二:外部迭代器

// 外部迭代器var Iterator = function(obj) {  var current = 0,    next = function() {      current++;    },    isDone = function() {      return current >= obj.length;      },    getCurrentItem = function() {      return obj[current];    };  return {    next: next,    isDone: isDone,    getCurrentItem: getCurrentItem  };};// 比較函數var compareAry = function(iterator1, iterator2) {  while( !iterator1.isDone() && !iterator2.isDone() ){    if(iterator1.getCurrentItem() !== iterator2.getCurrentItem()) {      throw new Error("不相等");    }    iterator1.next();    iterator2.next();  }  console.log("相等");}compareAry(new Iterator([1, 2, 3]), new Iterator([1, 2, 4]));

四、終止迭代器

var each = function(ary, callback) {  for(var i = 0, l = ary.length; i < l; i++) {    if(callback.call(ary[i], i, ary[i]) === false) {      break;    }  }}each([1, 2, 4, 1], function(i, n) {  if(n > 3) {    return false;  }  console.log(n);});

五、應用(落地)

文件上傳,根據不同的瀏覽器獲取相應的上傳組件對象。
對比《JavaScript設計模式

主站蜘蛛池模板: 嘉定区| 吉安市| 三原县| 和静县| 海林市| 满城县| 中超| 永清县| 靖宇县| 衡阳市| 垣曲县| 五河县| 大足县| 宕昌县| 元阳县| 泾阳县| 元谋县| 河南省| 湘潭县| 常宁市| 临城县| 峡江县| 宜都市| 榆林市| 新乐市| 齐齐哈尔市| 太白县| 中江县| 萨嘎县| 蓝山县| 中方县| 诸暨市| 曲沃县| 石楼县| 岳池县| 阳曲县| 江山市| 桂阳县| 济源市| 梁山县| 衡南县|