迭代器
在js中,迭代器是一个具体的对象,这个对象要符合迭代器协议:
- 迭代器协议定义了产生一系列值(无论是优先还是无限个)的标准方式
- 有一个特定的next方法,next方法有如下要求:
- 一个无参数函数,返回一个应当拥有以下两个属性的对象
- done: 如果迭代器可以产生序列中的下一个值,则为
false,如果迭代器已将序列迭代完毕,则为true - 迭代器返回的任何 JavaScript 值。done 为 true 时可省略
const friends = ["lilei", "kobe", "james"]
// 创建一个迭代器,用于迭代friends
let index = 0
const friendsIterator = {
next: function() {
if (index < friends.length) {
return { done: false, value: friends[index++] }
} else {
return { done: true, value: undefined }
}
}
}
console.log(friendsIterator.next()) // { done: false, value: 'lilei' }
console.log(friendsIterator.next()) // { done: false, value: 'kobe' }
console.log(friendsIterator.next()) // { done: false, value: 'james' }
console.log(friendsIterator.next()) // { done: true, value: undefined }
// -----------------------------------------
// 封装一个函数
function createArrayIterator(arr) {
let index = 0
return {
next: function() {
if (index < arr.length) {
return { done: false, value: arr[index++] }
} else {
return { done: true, value: undefined }
}
}
}
}
const friendsIterator = createArrayIterator(friends)
console.log(friendsIterator.next())
可迭代对象
- 当一个对象实现了iterable protocol协议时,它就是一个可迭代对象
- 这个对象的要求是必须实现
@@iterator方法,在代码中我们使用Symbol.iterator访问该属性;
const info = {
friends: ["lilei", "kobe", "james"],
[Symbol.iterator]: function() {
let index = 0
return {
next: () => {
if (index < this.friends.length) {
return { done: false, value: this.friends[index++] }
} else {
return { done: true, value: undefined }
}
}
}
}
}
// 数组本身是一个可迭代对象
const names = ["abc", "cba", "nba"]
// 获取可迭代的函数
console.log(names[Symbol.iterator]) // [Function: values]
// 调用可迭代函数, 获取到迭代器
const iterator = names[Symbol.iterator]()
console.log(iterator.next())