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上,每一信息资源都有统 ...
随机推荐
- centos下搭建redis集群
必备的工具: redis-3.0.0.tar redis-3.0.0.gem (ruby和redis接口) 分析: 首先,集群数需要基数,这里搭建一个简单的redis集群(6个redis实 ...
- iOS 发布证书提示 此证书的签发者无效 解决办法
1. 打开钥匙串 查看发布证书 都是提示 此证书的签发者无效 解决办法 : 2. 到了 第 4 步骤 再去 查看 发布证书 就会 显示 此证书有效 3. 如果还不可以 就 把 Apple W ...
- [刷题]算法竞赛入门经典(第2版) 6-9/UVa127 - "Accordian" Patience
题意:52张牌排一行,一旦出现任何一张牌与它左边的第一张或第三张"匹配",即花色或点数相同,则须立即将其移动到那张牌上面,将其覆盖.能执行以上移动的只有压在最上面的牌.直到最后没有 ...
- 进制转换,杭电0j-2031
进制转换,杭电0j-2031原题地址:http://acm.hdu.edu.cn/showproblem.php?pid=2031 [Problem Description] 输入一个十进制数N,将它 ...
- 如何用php实现简单的文件上传功能?(带图解)
如图所示:点击浏览出现选择文件的对话框,将所选文件上传到保存文件的文件. 关键点:文件上传的图解: 代码: <!DOCTYPE html> <html> <head&g ...
- 如何使用Handler
什么是Handler? Handler可以发送和处理消息对象或Runnable对象,这些消息对象和Runnable对象与一个线程相关联.每个Handler的实例都关联了一个线程和线程的消息队列.当创建 ...
- 基于Babylonjs自制WebGL3D模型编辑器
一.总述 当代WebGL编程所使用的3D模型大多是从3DsMax模型或Blender模型转化而来,这种工作模式比较适合3D设计师和3D程序员分工配合的场景.但对于单兵作战的WebGL爱好者来讲这种模式 ...
- Java Regex match IP address
Reference: [1] https://www.mkyong.com/regular-expressions/how-to-validate-ip-address-with-regular-ex ...
- 026 hibernate操作树形结构
树形结构:也就是目录结构,有父目录.子目录.文件等信息,而在程序中树形结构只是称为节点. 一棵树有一个根节点,而根节点也有一个或多个子节点,而一个子节点有且仅有一个父节点(当前除根节点外),而且也存在 ...
- spring-线程池(3)
一.初始化 1,直接调用 import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy; import org.springframe ...