1、Iterator遍历器
遍历器的作用就是统一的接口机制,来处理所有不同的数据结构
遍历器(Iterator)就是这样一种机制。它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署Iterator接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)。
Iterator的作用有三个:
- 为各种数据结构,提供一个统一的、简便的访问接口;
- 使得数据结构的成员能够按某种次序排列;
- ES6创造了一种新的遍历命令
for...of
循环,Iterator接口主要供for...of
消费;
2、Iterator的模拟封装
function makeIterator(array) {
//起始下标
var nextIndex = 0;
return {
//封装的next方法
next : function () {
return nextIndex < array.length ?
{value:array[nextIndex++],done:false} :
{value:undefined,done:true};
}
}
}
//注册iterator
var it = makeIterator(['1','54','154','15','48']);
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
上图中的{value:**,done:false}这种格式的返回就是所谓的iterator接口的规则,value表示当前这次遍历出来的值,done表示遍历是否结束。false为未结束,true为已结束
Iterator的遍历过程
- 创建一个指针对象,指向当前数据结构的起始位置。也就是说,遍历器对象本质上,就是一个指针对象。
- 第一次调用指针对象的next方法,可以将指针指向数据结构的第一个成员。
-
第二次调用指针对象的next方法,指针就指向数据结构的第二个成员。
-
不断调用指针对象的next方法,直到它指向数据结构的结束位置。
3、数据结构的默认Iterator接口
ES6规定,默认的Iterator接口部署在数据结构的Symbol.iterator属性,或者说,一个数据结构只要具有Symbol.iterator属性,就可以认为是“可遍历的”(iterable)
比如数组
<script>
var arr = [1, 2, 5, 36, 4]
console.log(arr)
</script>
遍历数组
<script>
var arr = [1, 2, 5, 36, 4]
console.log(arr)
var it = arr[Symbol.iterator]();
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
console.log(it.next());
</script>
在ES6中,原生具备Iterator接口的数据结构:数组、某些类似数组的对象、String、Set和Map结构
4、 for..of循环
一个数据结构只要部署了Symbol.iterator属性,就被视为具有iterator接口,就可以用for...of循环遍历它的成员
数组
var arr = [5,48,48,5,9,464]
for(let item of arr){
console.log(item)
}
arguments 对象
function printArgs() {
for(let item of arguments){
console.log(item)
}
}
printArgs("a","b","c")
除了for...of循环以外,扩展运算符(...)、解构赋值和Array.from方法内部调用的,都是遍历器接口