ES6中的遍历器

202 阅读6分钟

什么是遍历器

在es6中又新增了set, map,再加上Array和object,js中能表示“集合”的数据类型一共有了四种,他们又可以组合成更多的数据结构。这样我们就需要有一种统一的接口机制,来处理不同的数据结构。

遍历器就是这样的一种机制。它是一种接口,为各种数据结构提供统一的访问机制 。任何数据结构只要部署iterator接口,就可以完成遍历操作

遍历器能够解决哪些问题

  1. 为各种数据结构提供了一个统一简便的访问接口
  2. 能够让数据结构成员按照某种顺序排列
  3. es6创建了for...of遍历,Iterator主要供for...of消费

遍历器底层原理

  1. iterator的遍历过程
    1. 首先创建一个指针对象,指向当前数据结构的起始位置
    2. 其次调用指针对象next方法,移动指针,指向第二个成员
    3. 然后调用指针对象next方法,移动指针,指向第三个成员
    4. 以此类推,不断调用next方法,直至指向最后一个成员
  2. 遍历器的本质就是一个指针对象,该对象有一个next方法,调用该方法会返回一个具有valuedone的对象。value表示当前的成员的值,done表示遍历是否结束。遍历完成后再次调用next方法,会返回{value: undefined, done: true}
// demo1 模拟实现iterator接口
function makerIterator (array) {
	let i = 0
	return {
		next: function () {
			return i < array.length ?
				{value: array[i++], done: false} :
				{value: undefined, done: true}
		}
	}
}
const iterator = makerIterator(['a', 'b'])
console.log(iterator.next()) // { value: 'a', done: false}
console.log(iterator.next())// { value: 'b', done: false}
console.log(iterator.next())// { value: undefined, done: done}

遍历器的实现和应用

一种数据结构只要部署了遍历器接口,我们就认为它是可遍历的

es6中默认的遍历器接口

  • es6默认的遍历器接口部署在数据结构的Symbol.iterator属性。Symbol.iterator属性本身是一个函数,执行函数就会返回一个遍历器。
  • Symbol.iterator,它是一个表达式,返回Symbol对象的iterator属性,这是一个预定义好的、类型为 Symbol的特殊值,所以要放在方括号内
  • es6中有些数据结构原生具有遍历器接口,它们能直接通过for...of遍历。
    1. Array
    2. Set,
    3. Map,
    4. string,
    5. arguments
    6. NodeLists
    7. TypedArray

调用iterator接口的场合

  1. 解构赋值
  • 多数组合set进行解构赋值时,会默认调用Symbol.iterator
let a = new Set().add('a').add('b').add('c')
let [x, y] = a // x: 'a' y: 'b'
let [z, ...rest] = a // z: 'a', rest: ['b','c']
  1. 扩展运算符
  • 使用...时也会调用Symbol.iterator
const str = 'string'
const a = [...str] // ['s', 't', 'r', 'i', 'n', 'g']

cons arr = ['a', 'b']
const b = ['c', ...arr, 'd']
  1. yield*
  • yield* 后面跟的是一个可遍历的结构,它会调用该数据结构的遍历器接口
let generator = function* () {
  yield 1;
  yield* [2,3,4];
  yield 5;
};

const iterator = generator();

iterator.next() // { value: 1, done: false }
iterator.next() // { value: 2, done: false }
iterator.next() // { value: 3, done: false }
iterator.next() // { value: 4, done: false }
iterator.next() // { value: 5, done: false }
iterator.next() // { value: undefined, done: true }

4.其它场合

  • 一些接受数组作为参数的的场合都调用了遍历器接口
1. for...of
2. Array.from()
3. Map(), Set(), WeakMap(), WeakSet()
4. Promise.all()
5. Promise.race()

字符串的Iterator接口

  • 字符串是一个类似数组的对象,也原生具有 Iterator 接口。基本字符串不能修改原生的遍历器接口,通过构造函数声明的字符串可以修改
const str = new String("hi");
// const str = 'hi'

[...str] // ["h", "i"]

str[Symbol.iterator] = function() {
  return {
    next: function() {
      if (this._first) {
        this._first = false;
        return { value: "bye", done: false };
      } else {
        return { done: true };
      }
    },
    _first: true
  };
};

[...str] // ["bye"]
str // "hi"

iterator和generator

let obj = {
 * [Symbol.iterator] () {
   yield 1
   yield 2
   yield 3
 }
}

for (let value of obj) {
   console.log(value)
}

遍历器对象的return()和throw()

  • 是否部署都是可选的
  1. return方法。通常此方法被调用时,意味通知iterator对象,调用者不会再调用next方法了。使用场景就是,for...of提前退出循环(通常是执行了break,或者出错了。)
  2. throw方法。调用此方法会通知Iterator对象调用者已检测到错误情况。

for...of 循环

  1. for...of循环内部调用的是Symbol.iterator方法,所有只要数据结构部署了iterator接口就能通过for...of遍历
  2. for...of循环可以使用的范围包括数组、Set 和 Map 结构、某些类似数组的对象(比如arguments对象、DOM NodeList 对象)、后文的 Generator 对象,以及字符串。
  1. 给boolean添加一个遍历器对象
const isTrue = new Boolean(true)
isTrue[Symbol.iterator] = function () {
	return {
		next: function () {
			if (this.first) {
				this.first = false
				return {
					value: 'hahaha',
					done: false
				}
			} else {
				return {
					value: undefined,
					done: true
				}
			}
		},
		first: true
	}
}
for (let value of isTrue) {
	console.log(value)
}
  1. 数组遍历器对象
// 数组遍历器对象
const arr = ['hello', 'world']
for (let value of arr) {
	console.log(value)
}

const obj = {}
obj[Symbol.iterator] = arr[Symbol.iterator].bind(arr)

for (let value of obj) {
	console.log(value)
}

  1. Set和Map结构
  • 首先他们的遍历顺序都是按照添加的顺序
  • Set结构遍历,返回的是一个值,Map结构遍历,返回的是一个包含键名和键值的数组
const set = new Map().set('a', 1).set('b', 2)
for (let [key, value] of set) {
	console.log(`${key} : ${value}`)
}
  1. 计算生成的数据结构 ES6 的数组、Set、Map 结构都部署的以下三个方法
  • entries()返回一个遍历器对象,用来遍历[键名, 键值]组成的数组。对于数组,键名就是索引值;对于 Set,键名与键值相同。Map 结构的 Iterator 接口,默认就是调用entries方法。
  • keys()返回一个遍历器对象,用来遍历所有的键名。
  • values()返回一个遍历器对象,用来遍历所有的键名
  1. 类数组的对象
  • 类似数组的对象包括好几类。字符串、DOM NodeList 对象、arguments对象,都有原生部署iterator
  • 对于没有部署的类数组对象,要想通过for...of遍历,可以先转换为数组。可通过下面方法转换为数组
    1. Array.from()
    2. Array.prototype.slice.apply(arg)
  1. 对象
  • 对于普通对象来说,并没有部署遍历器接口,直接通过for...of遍历会报错。
  • 如果想要通过for...of遍历可以有多种方式
    1. 通过Object.keys()获取键名
      for (var key of Object.keys(someObject)) {
        console.log(key + ': ' + someObject[key]);
      }
    
    1. 使用 Generator 函数将对象重新包装一下
    function* entries(obj) {
      for (let key of Object.keys(obj)) {
       yield [key, obj[key]];
      }
    }
      
    for (let [key, value] of entries(obj)) {
      console.log(key, '->', value);
    }
    

和其它循环的对比

  1. for循环。写法较为麻烦
  2. 数组的forEach()。无法跳出循环,return,break,contine命令都不能奏效
  3. for...in是为遍历对象专门设计的。缺点如下:
    1. 键名都会被转成字符串
    2. 会遍历原型上的属性
    3. 顺序任意
    function A() {
        this.a = '1'
    }
    function B() {
    	this.b = '2'
    }
    B.prototype = new A()
    const b = new B()
    b.c = 12
    for (let key in b) {
    	console.log(key)
    	// b string
    	// c string
    	// 1 string
    	// a string
    }
    
  4. for...of
    1. 没有for...in的缺点
    2. 能够通过break跳出循环。不同于forEach方法,它可以与break、continue和return配合使用。
    3. 统一的遍历接口