迭代器模式 - Iterator

111 阅读1分钟

一、定义

迭代器模式是指提供一种方法顺序访问一个聚合对象中的各个元素,而又不需要暴露该对象的内部表示。

二、核心

在使用迭代器模式之后,即使不关心对象的内部构造,也可以按顺序访问其中的每个元素。
简单理解:统一“集合”型数据结构的遍历接口,实现可循环遍历获取集合中各数据项(不关心数项中的数据结构)。
例如:TodoList清单,每日清单有学习类、生活类、工作类等项目,清单列表只管罗列,不管类别。

三、实现

JS中的Array.prototype.forEach就是一个迭代器。

[1,2,3].forEach((item, index, arr) => {
  console.log(item, index, arr)
})

// 输出:
//  1 0 [ 1, 2, 3 ]
//  2 1 [ 1, 2, 3 ]
//  3 2 [ 1, 2, 3 ]

*仿写forEach

// 实现
Array.prototype.each = function (callback) {
  if (!callback) return;
  for (let i = 0; i < this.length; i++) {
    callback(this[i], i, this)
  }
}

// 使用
const ary = []; // 引申,为啥不注释会报错:Cannot read property 'each' of undefined
[1, 2].each((item, idx, array) => {
  console.log(`item: ${item}, index: ${idx}, array: ${array}`)
})

// 输出:
// item: 1, index: 0, array: 1,2
// item: 2, index: 1, array: 1,2

上面的写法为内部迭代器,所有也有外部迭代器的写法

// 外部迭代器
const each = function (array, callback) {
  if (!array || !callback)return;
  for(let i = 0; i < array.length; i++) {
    callback(array[i], i, array)
  }
}

// 使用
each([1, 5], (item, idx, array) => {
  console.log(`外部迭代:item: ${item}, index: ${idx}, array: ${array}`)
})

// 输出:
// 外部迭代:item: 1, index: 0, array: 1,5
// 外部迭代:item: 5, index: 1, array: 1,5

跳转:设计模式目录