1.Iterator(遍历器)的概念
JS 原有的表示集合的数据结构,主要是 Array与Object,但ES6 又添加了Map与Set,这样就有了四种数据集合,我们可以组合使用它们,定义自己的数据结构。
遍历器(Iterator)它是一种接口,为各种不同的数据结构提供统一的访问机制。任何数据结构只要部署 Iterator 接口,就可以完成遍历操作(即依次处理该数据结构的所有成员)。
Iterator 的遍历过程
- 创建一个指针对象,指向当前数据结构的起始位置。也就是说,Iterator对象本质上,就是一个指针对象。可以理解为指向内存地址
- 第一次调用指针对象的next()方法,可以将指针指向数据结构的第一个成员
- 不断调用指针对象的next()方法,直到它指向数据结构的结束位置。
每一次调用执行 next() 方法,都会返回数据结构的当前成员的信息。具体来说,就是返回一个包含value与done两个属性的对象。其中,value属性是当前成员的值,done属性是一个布尔值,表示遍历是否结束。
let colors = ['red','blue','green'];
//转化为 Iterator 遍历器
colors = colors[Symbol.iterator]() // colors.entries()
colors.next() // {value: "red", done: false}
colors.next() // {value: "blue", done: false}
colors.next() // {value: "green", done: false}
colors.next() // {value: undefined, done: true}
2.默认 Iterator 接口
Iterator 接口的目的,就是为所有数据结构,提供了一种统一的访问机制,即 for...of 循环。当使用for...of循环遍历某种数据结构时,该循环会自动去寻找 Iterator 接口。
原生具备 Iterator 接口的数据结构如下。
- Array
- Map
- Set
- String
- NodeList
3.for...of 循环
以前有三种方式来遍历数组
const arr = ['red', 'green', 'blue'];
for(let i = 0; i < arr.length; i++){
console.log(arr[i]); // red green blue
}
//缺点是不能终止循环
arr.forEach(item =>{
//if(item === 'red'){
//break;
//continue
//}
console.log(arr[i]); // red green blue
})
arr.color = 'yellow';
for(let index in arr){
//这样显然不是我们想要的结构
console.log(arr[index]); // red green blue yellow
}
for...of循环本质上就是调用 Iterator 接口产生的遍历器,可以用下面的代码证明。
const arr = ['red', 'green', 'blue'];
for(let v of arr) {
console.log(v); // red green blue
}
JS原有的 for in 循环,只能获得对象的键名,不能直接获取键值。ES6 提供for...of 循环,允许遍历获得键值。
var arr = ['a', 'b', 'c', 'd'];
for (let a in arr) {
console.log(a); // 0 1 2 3
// 如果你想获取值则需要这样做
console.log(arr[a])
}
for...of 循环调用遍历器接口,数组的遍历器接口只返回具有数字索引的属性。这一点跟for...in 循环也不一样。 entries() 创建一个可迭代对象 Iterator , 该对象包含了数组的键值对
const arr = ['red', 'green', 'blue'];
arr.foo = '你好';
// || for (let [index,item] of arr.entries()) {
for (let a of arr.entries()) {
console.log(a); // [0, "red"],[1, "green"],[2, "blue"]
}
上面代码中,for...of 循环不会返回数组arr的foo属性。
for of 循环可以用于 字符串、数组、NodeList、Map、Set,很遗憾暂时还不支持对象
往期内容
希望大家能一块分享一些文章,在公众号里面私信我吧!
