3

行为型:迭代器模式 - 风吹De麦浪

 1 year ago
source link: https://www.cnblogs.com/longbensong/p/17308094.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

  迭代器模式提供一种方法按顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。迭代器模式是目的性极强的模式它主要是用来解决遍历问题。

es6 中的迭代器

  JS原生的集合类型数据结构,有Array(数组)和Object(对象),在ES6中,又新增了Map和Set。四种数据结构各自有着自己的内部实现,但对于使用者,我们希望以同样的一套规则去遍历它们,所以ES6在推出新数据结构的同时也推出了一套统一的接口机制——迭代器(Iterator)

  es6 中统一了迭代器迭代接口,任何数据结构只要具备Symbol.iterator属性(这个属性就是Iterator的具体实现,它本质上是当前数据结构默认的迭代器生成函数),就可以被遍历,确切的说是被for...of...循环和迭代器的next方法遍历,for...of...的背后正是对next方法的反复调用。

  在ES6中,针对Array、Map、Set、String、TypedArray、函数的 arguments 对象、NodeList 对象这些原生的数据结构都可以通过for...of...进行遍历。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK