概念:iterator 是一种接口机制, 为各种不同的数据结构提供统一的访问机制
作用:
工作原理:
value 表示当前成员的值,done 对应的布尔值表示当前的数据的结构是否遍历结束。
当遍历结束的时候返回的 value 值是 undefined, done 值为 true
function myIterator(arr) {
let nextIndex = 0; // 记录指针的位置;
return {// 遍历器对象
next: function () {
return nextIndex < arr.length ? {value: arr[nextIndex++], done: false} : {value: undefined, done: true}
}
}
}
// 准备一个数据
let arr = [1,4,65,'abc'];
let iterator = myIterator(arr);
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
将 iterator 接口部署到指定的数据类型上,可以使用 for of 去循环遍历
如:数组、字符串、arguments、set 容器、map 容器
for (let i of arr){
console.log(i);
}
let string = 'asdf';
for (let i of string){
console.log(i)
}
function fun() {
for (let i of arguments){
console.log(i);
}
}
fun(1,4,5,'abc');
// 对象不可以迭代
let obj = {'username': 'janechelle','age': 18};
for (let i of obj){
console.log(i);
}
等同于在指定的数据结构内部署了 iterator 接口
当使用 for of 去遍历某一个数据结构的时候,首先去找 Symbol.iterator ,找到了就去遍历,没有找到的话不能遍历 xxx is not iterable
let targetData = {
[Symbol.iterator]: function () {
let nextIndex = 0; // 记录指针的位置;
return {// 遍历器对象
next: function () {
return nextIndex < arr.length ? {value: arr[nextIndex++], done: false} : {value: undefined, done: true}
}
}
}
}
使用三点运算符,解构赋值,默认去调用 iterator 接口
let arr2 = [1,6];
let arr3 = [2,3,4,5,];
arr2 = [1, ...arr3, 6];
console.log(arr2);
let [a, b] = arr2;
console.log(a,b);