Gist - ES6 Iterator
Introduction
Iterator is one of the most common design modes in daily development. Let's explore the iterator continent in the javacript world, here we go!
Gist Iterator Mode
It's the basic iterator mode concept:

And it's like this in javascript world:

Grammar rules
Attention
Assume that "iterable" is an adjective, and "iterableFn" is a iterable.
It's a little confusing when lots of "iterable" appear at the same time.
Relation between iterable and iterator
Iterator can be created by iterableFn(an iterable), iterableFn belongs to iterable sources.
Iterables
Iterable sources
- Array
- String
- Map
- Set
- Dom Elements
- Arguments
Get iterableFn(used to generate iterator)
IterableFn can be derived from iterable source by its property: Symbol.iterator, for example: const iterableFn = [][Symbol.iterator]
Symbol.iterator
A method that returns the default Iterator for an object. Called by the semantics of the for-of statement.
/** Test in chrome 55 **/
// Array
console.log( [][Symbol.iterator] ) // function values() { [native code] }
// String
console.log( ''[Symbol.iterator] ) // function [Symbol.iterator]() { [native code] }
// Map
console.log( new Map([[]])[Symbol.iterator] ) // function entries() { [native code] }
// Set
console.log( new Set([])[Symbol.iterator] ) // function values() { [native code] }
// Dom elements
console.log( document.getElementsByTagName('body')[Symbol.iterator] ) // function values() { [native code] }
// arguments
function test() {
console.log( arguments[Symbol.iterator] )
}
test(1, 2, 3) // // function values() { [native code] }
Iterable sources' consumers
Follow consumers' implementations mainly depend on iterables.Howerver, the examples are irrelevant to topic.
- for of
for(const i in [1, 2]) {
cosnole.log(i)
}
// 1
// 2
- ...(The spread opeartor)
console.log( [..."ab"] ) // ["a", "b"]
- Array.from
console.log( Array.from("ab") ) // ["a", "b"]
Iterators
Iterator is common used, as to decouple algorithms.
Iterator = iterableFn()
After iterable's implementation, it returns an object called iterator, which uses "next" method to iterate.
/** Test in chrome 55 **/
// Array
console.log( [][Symbol.iterator]() ) // ArrayIterator {}
// String
console.log( ''[Symbol.iterator]() ) // StringIterator {}
// Map
console.log( new Map([[]])[Symbol.iterator]() ) // MapIterator {[undefined, undefined]}
// Set
console.log( new Set([])[Symbol.iterator]() ) // SetIterator {}
// Dom elements
console.log( document.getElementsByTagName('body')[Symbol.iterator]() ) // ArrayIterator {}
// arguments
function test() {
console.log( arguments[Symbol.iterator]() )
}
test(1, 2, 3) // ArrayIterator {}
Add value and Implement method "next":
/** Test in chrome 55 **/
// Array
console.log( [1, 2][Symbol.iterator]().next() ) // {value: 1, done: false}
// String
console.log( 'ab'[Symbol.iterator]().next() ) // {value: 'a', done: false}
// Map
console.log( new Map([[1, 'a']])[Symbol.iterator]().next() ) // {value: [1, 'a'], done: false}
// Set
console.log( new Set([1, 1, 2])[Symbol.iterator]().next() ) // {value1: , done: false}
// Dom elements
console.log( document.getElementsByTagName('body')[Symbol.iterator]().next() ) // {value: body(dom), done: false}
// arguments
function test() {
console.log( arguments[Symbol.iterator]().next() )
}
test(1, 2, 3) // {value: 1, done: false}
Iterator = generator()
Setting iterator mutually again and again seems inefficient, syntactic sugar is needed. Fortunately, ES6 provides the useful "generater"
function* iteratorMaker() {
yield 1
yield 2
}
const iterator = iteratorMaker()
console.log( iterator ) // iteratorMaker {[[GeneratorStatus]]: "suspended", [[GeneratorReceiver]]: Window, [[GeneratorLocation]]: Object}
console.log( iterator.next() ) // {value: 1, done: false}
console.log( iterator.next() ) // {value: 2, done: false}
console.log( iterator.next() ) // {value: undefined, done: true}
Application
Iterator can be applied in wide situations, there's a sample to generate increasing id numbers.
function* idIteratorMaker() {
let id = 0
while (true) {
yield id++
}
}
function create(idIterator) {
return idIterator.next().value
}
const idIterator = idIteratorMaker()
const a = create(idIterator)
const b = create(idIterator)
const c = create(idIterator)
console.log(a) // 0
console.log(b) // 1
console.log(c) // 2
Conclusion
Obviously, iterator makes codes more readable and matainable.
Reference
- http://exploringjs.com/es6/ch_iteration.html#sec_iterating-language-constructs
- https://tc39.github.io/ecma262/#table-1
Gist - ES6 Iterator的更多相关文章
- ES6—— iterator和for-of循环
Iterator 遍历器的作用:为各种数据结构,提供一个同意的,简便的访问接口.是的数据结构的成员能够按某种次序排列.ES6 新增了遍历命令 for...of 循环,Iterator接口主要供 for ...
- es6 -- Iterator 和 for...of 循环
1:Iterator(遍历器)的概念 JavaScript 原有的表示“集合”的数据结构,主要是数组(Array)和对象(Object),ES6 又添加了Map和Set.这样就有了四种数据集合,用户还 ...
- es6 Iterator和for...of循环
javascript表示集合的数据结构有 es5: array object es6: map set, 一共4种数据集合 需要一种统一的接口机制来处理所有不同的数据结构 遍历器就是这样一种机制,它是 ...
- Gist - ES6 Proxy
Introduction "Proxy" is a frequently used pattern in both virtual world and real world. Th ...
- ES6 iterator 迭代器
iterator使用TypeScript 的描述: interface Iterable { [Symbol.iterator]() : Iterator, } interface Iterator ...
- ES6(Iterator 和 for...of 循环)
Iterator 和 for...of 循环 1.什么是 Iterator 接口 Iterator 接口功能:用一种相同办法的接口让不同的数据结构得到统一的读取命令的方式 2.Iterator的基本用 ...
- Gist - ES6 Promise
The concept of "Promise" Promise is used to asynchronous computations. Introduction " ...
- ES6 Iterator
不同数据集合怎么用统一的方式读取 可以用for...of循环了
- nodejs入门API之url模块+querystring模块
关于URL的一些基础内容 URL模块的API解析 URL的参数URLSearchParams类 querystring模块 一.关于URL的一些基础内容 1.1 定义: 在WWW上,每一信息资源都有统 ...
随机推荐
- Redis学习-持久化
Redis 提供了多种不同级别的持久化方式: RDB 持久化可以在指定的时间间隔内生成数据集的时间点快照(point-in-time snapshot). AOF 持久化记录服务器执行的所有写操作命令 ...
- c#接口使用详解
c#接口使用详解 c#中接口隐式与显示实现 c#中接口可以隐式实现.显示实现,隐式实现更常使用.显示实现较少使用 其区别在于 显示实现避免接口函数签名冲突 显示实现只可以以接口形式调用 显示实现其子类 ...
- 浅谈 Java Xml 底层解析方式
XML 使用DTD(document type definition)文档类型来标记数据和定义数据,格式统一且跨平台和语言,已成为业界公认的标准. 目前 XML 描述数据龙头老大的地位渐渐受到 Jso ...
- Jenkins+Tomcat+svn+maven自动化构建简单过程
搭建好jenkins自动化构建之后,点击立即构建,即可将svn服务器上的源码自动编译构建,并打成war包,然后将这个war包以及编译好的项目复制到指定服务器的tomcat容器里,当svn服务器的代码有 ...
- gitignore.io-程序猿值得拥有的智能生成gitignore文件的秘密武器
gitignore.io Create useful .gitignore files for your project by selecting from 360 Operating System, ...
- libsvm参数选择
以前接触过libsvm,现在算在实际的应用中学习 LIBSVM 使用的一般步骤是: 1)按照LIBSVM软件包所要求的格式准备数据集: 2)对数据进行简单的缩放操作: 3)首要考虑选用RBF 核函数: ...
- Vuejs实例-02Vue.js项目集成ElementUI
Vuejs实例-02Vue.js项目集成ElementUI 0:前言 vue.js的UI组件库,在git上有多个项目,我见的使用者比较多的是iView和Element.两个组件库,组件都很丰富. 官网 ...
- 【AngularJS中的自定义服务service VS factory VS provider】---它们的区别,你知道么?
在介绍AngularJS自定义服务之前,我们先来了解一下AngularJS~ 学过HTML的人都知道,HTML是一门很好的伪静态文本展示设计的声明式语言,但是,要构建WEB应用的话它就显得乏力了. 而 ...
- 用node编写自己的cli工具
工作中接到新项目,开发前都需要先规划项目目录,然后一个个创建文件,搭建sass编译环境,下载jquery,Swiper等类库... 这些准备工作都要花上不少时间.每做一个项目,都会遇到同样的问题,再重 ...
- nginx配置优化+负载均衡+动静分离详解
nginx配置如下: #指定nginx进程运行用户以及用户组user www www;#nginx要开启的进程数为8worker_processes 8;#全局错误日志文件#debug输出日志最为详细 ...