Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript设计模式(四):迭代器模式 #24

Open
yangrenmu opened this issue Apr 28, 2020 · 0 comments
Open

JavaScript设计模式(四):迭代器模式 #24

yangrenmu opened this issue Apr 28, 2020 · 0 comments
Labels

Comments

@yangrenmu
Copy link
Owner

定义

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

迭代器模式有点像那个遍历。for 循环差不多吧。细分的话有内部迭代器和外部迭代器。

内部迭代器

内部迭代器,在内部就定义好了迭代规则,外部直接调用即可。所以使用起来,是很方便的。

function each(arr, callback) {
  for (let i = 0; i < arr.length; i++) {
    callback(arr[i])
  }
}

each([1, 2, 3], function (v) {
  console.log(v) // 1 2 3
})

外部迭代器

外部迭代器,相比于内部迭代器,增加了一些调用复杂度,同时带来的好处是,增强了迭代器的灵活性,我们可以手动控制迭代的过程或者顺序。

function* generatorEach(arr) {
  for (let value of arr) {
    yield console.log(value);
  }
}

let each = generatorEach(['Angular', 'React', 'Vue']);
each.next(); // Angular
each.next(); // React
each.next(); // Vue
@yangrenmu yangrenmu added the mode label Apr 28, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant