Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[es6] - Iterator遍历器 #15

Open
Jmingzi opened this issue Nov 22, 2017 · 0 comments
Open

[es6] - Iterator遍历器 #15

Jmingzi opened this issue Nov 22, 2017 · 0 comments

Comments

@Jmingzi
Copy link
Owner

Jmingzi commented Nov 22, 2017

1. Iterator(遍历器)的概念

iterator是一种统一的接口机制,用来处理4种数据结构:Array,Object,Set,Map。

任何数据结构只要部署 Iterator 接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)。

其作用:

  • 为各种数据结构,提供一个统一的、简便的访问接口;
  • 使得数据结构的成员能够按某种次序排列;
  • ES6 创造了一种新的遍历命令for...of循环,Iterator 接口主要供for...of消费。

2. 默认 Iterator 接口

"只要部署 Iterator 接口"的意思是

一个数据结构只要具有Symbol.iterator属性,就可以认为是“可遍历的”(iterable)。Symbol.iterator属性本身是一个函数,就是当前数据结构默认的遍历器生成函数。执行这个函数,就会返回一个遍历器。至于属性名Symbol.iterator,它是一个表达式,返回Symbol对象的iterator属性,这是一个预定义好的、类型为 Symbol 的特殊值,所以要放在方括号内(参见 Symbol 一章)。

原生具有Symbol.iterator属性的数据结构有

  • Array
  • Map
  • Set
  • String
  • TypedArray
  • 函数的 arguments 对象
  • NodeList 对象

不具备的是Object对象,我们可以手动给实例加上Symbol.iterator属性

var likeArray = {
   0: 1,
   1: 2,
   length: 2,
   [Symbol.iterator]: Array.prototype[Symbol.iterator]
}

for (let item of likeArray) {
  console.log(item)  // 1, 2
}

[...likeArray]  // 1, 2

likeArray可以称之为类似数组对象,具有iterator接口,所有可以遍历。非类似数组的对象虽然也可以遍历,但是并不能取到值了

var notLikeArray = {
   a: 1,
   b: 2,
   length: 2,
   [Symbol.iterator]: Array.prototype[Symbol.iterator]
}

for (let item of notLikeArray) {
  console.log(item)  // undefined, undefined
}

[...notLikeArray] // undefined, undefined

3. Iterator 接口使用场合

  • 解构赋值

对数组和 Set 结构进行解构赋值时,会默认调用Symbol.iterator方法。

let set = new Set().add('a').add('b').add('c')

let [x,y] = set
// x='a'; y='b'

let [first, ...rest] = set
// first='a'; rest=['b','c']
  • 扩展运算符
  • yield*
  • 其他场合
    由于数组的遍历会调用遍历器接口,所以任何接受数组作为参数的场合,其实都调用了遍历器接口。下面是一些例子。
- for...of
- Array.from()
- Map(), Set(), WeakMap(), WeakSet()(比如new Map([['a',1],['b',2]]))
- Promise.all()
- Promise.race()
@Jmingzi Jmingzi changed the title es6 - Iterator 和 for...of 循环 [es6] - Iterator 和 for...of 循环 Nov 22, 2017
@Jmingzi Jmingzi changed the title [es6] - Iterator 和 for...of 循环 [es6] - Iterator遍历器 Nov 22, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant