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上,每一信息资源都有统 ...
随机推荐
- Linux主机通过代理服务器进行网络连接
公司的不允许访问外网,但是访问外网需要配置代理,window配置均好配置,在Linux的命令行底下,一般的程序都是使用http_proxy和ftp_proxy这两个环境变量来获得代理设置的.1.在/e ...
- SAP ECC EHP7 RFC 发布成WebService
1.说明介绍 本文将RFC发布成WebService的详细步骤,参考了百度经验http://jingyan.baidu.com/article/8275fc867c9e2946a13cf66c.htm ...
- 每天一道Java题[10]
题目 阐述创建线程最常用的两种方法及其对比. 解答 方法一:继承Thread类实现 步骤: 创建Thread类的子类,如MyThread. 重写Thread类的run()方法. 实例化MyThread ...
- JAVA网络编程TCP通信
Socket简介: Socket称为"套接字",描述IP地址和端口.在Internet上的主机一般运行多个服务软件,同时提供几种服务,每种服务都打开一个Socket,并绑定在一个端 ...
- 网络编程应用:基于TCP协议【实现文件上传】--练习
要求: 基于TCP协议实现一个向服务器端上传文件的功能 客户端代码: package Homework2; import java.io.File; import java.io.FileInputS ...
- Ch1. Intro to Programming
1-1 Input three integers and output the average number. Keep three decimal places. #include<stdi ...
- cpp(第三章)
1.使用{}初始化时,{}若为空则默认初始化为0,至于防范类型转化错误 2.int对计算机而言最为自然的长度,处理起来效率最高的长度.int可能是short(16位)也可能是long(32位),在知道 ...
- Canvas学习系列一:初识canvas
最近你开始在学习canvas,打算把学习canvas的整个学习过程当中的一些笔记与总结记录下来,如有什么不足之处还请大神们多多指出. 1. 认识canvas Canvas元素的出现,可以说开启的Web ...
- Linux SSH安全技巧
SSH服务器配置文件是/etc/ssh/sshd_conf.在你对它进行每一次改动后都需要重新启动SSH服务,以便让改动生效. 1.修改SSH监听端口默认情况下,SSH监听连接端口22,攻击者使用端口 ...
- Vue爬坑之vuex初识
在 Vue.js 的项目中,如果项目结构简单, 父子组件之间的数据传递可以使用 props 或者 $emit 等方式 http://www.cnblogs.com/wisewrong/p/62660 ...