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上,每一信息资源都有统 ...
随机推荐
- 使用fontawesome图标
我每次找图标时都是在阿里的开源图标库中找的,但是使用起来不是很方便.而我发现了fontawesome之后,觉得实在不错,所以分享给大家. 这是一些参考的文档. fontawesome下载与使用介绍 ...
- 基于require+knockout的webapp结构设计
*********************************************************************************** 一.项目结构: Webapp - ...
- 命令模式(Command Pattern)
命令模式属于对象的行为模式.命令模式又称为行动(Action)模式或交易(Transaction)模式.命令模式把一个请求或者操作封装到一个对象中.命令模式允许系统使用不同的请求把客户端参数化,对请求 ...
- XAF_GS_01_准备环境
各位久等了,接下来我们开始学习XAF入门的第一节,搭建XAF的环境 Setp 1 第一步不是创建什么项目,而是先安装我们的XAF环境也就是安装DevExpress 由于笔者安装的是16.2.3所以演示 ...
- CentOS系统搭建gitolite服务
1.安装相关支持软件 a.$yum install perl-Time-HiRes openssh-server perl -y b.$yum -y install git 2.服务端操作:创建git ...
- 【JAVAWEB学习笔记】16_session&cookie
会话技术Cookie&Session 学习目标 案例一.记录用户的上次访问时间---cookie 案例二.实现验证码的校验----session 一.会话技术简介 1.存储客户端的状态 由一个 ...
- Java中的栈上分配
博客搬家自https://my.oschina.net/itsyizu/blog/ 什么是栈上分配 栈上分配是java虚拟机提供的一种优化技术,基本思想是对于那些线程私有的对象(指的是不可能被其他线程 ...
- 2-LPC1778之GPIO
其实这篇文章主要是介绍自己为其写的GPIO库,自己借鉴了原子写的STM32,野火写的K60,还有LPC官方库,然后按照自己平时用的,然后写了一个..其实写库的主要目的是为了方便(主要是方便操作)以后自 ...
- iOS storyBoard中tableViewCell传值方法
一般在storyboard中传值通过identifier的值来控制segue的跳转和传值,但是,如果在tableView中,由于cell特别多,不可能创建n个identifier标识符,这里通过NSI ...
- (基础篇 走进javaNIO)第二章-NIO入门
在本章巾,我们会分别对 JDK 的BIO ,NIO 和JDK 1.7 最新提供的 NI02.0的使用进行详细说明 ,通过流程图和代 码讲解,让大 家体会到随着 Ja va 1/0 类库的 不断发展和改 ...