iterator(遍历器)的概念
JavaScript原有的表示“集合”的数据结构,主要是数组(Array)和对象(Object),ES6又添加了Map和Set。这样就有了四种数据集合,用户还可以组合使用它们,定义自己的数据结构,比如数组的成员是Map,Map的成员是对象。这样就需要一种统一的接口机制,来处理所有不同的数据结构。
遍历器(Iterator)就是这样一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署Iterator接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)。
Iterator的作用有三个:
一是为各种数据结构,提供一个统一的、简便的访问接口;
二是使得数据结构的成员能够按某种次序排列;
三是ES6创造了一种新的遍历命令for...of循环,Iterator接口主要供for...of消费。
Iterator的遍历过程
创建一个指针对象,指向当前数据结构的起始位置。也就是说,遍历器对象本质上,就是一个指针对象。
第一次调用指针对象的next方法,可以将指针指向数据结构的第一个成员。 第二次调用指针对象的next方法,指针就指向数据结构的第二个成员。 不断调用指针对象的next方法,直到它指向数据结构的结束位置。
每一次调用next方法,都会返回数据结构的当前成员的信息。具体来说,就是返回一个包含value和done两个属性的对象。其中,value属性是当前成员的值,done属性是一个布尔值,表示遍历是否结束。
下面模拟一个遍历器对象
const arr = [1,2,3]; function iterator(arr) { let index = 0; return { next: function () { return index < arr.length ? {value: arr[index++],done: false} : {value: undefined, done: true}; } } } const it = iterator(arr); console.log(it.next()); console.log(it.next()); console.log(it.next()); console.log(it.next()); console.log(it.next());
原生具备iterator接口的数据(可用for of遍历)
Array
let arr = [2,3,4,6] for(let i of arr) { console.log(i) }
arguments(遍历其他伪数组都可以)
function fun() { for (let i of arguments) { console.log(i) } } fun(1,2,3,45,6)
set容器
let s = new Set([1,2,3,4]) for (let i of s) { console.log(i) }
map容器
const m = new Map([ ['a',1], ['b',2] ]); for (let i of m) { console.log(i) }
String
let str = 'abcafdsaf' for(let i of str) { console.log(i) }