迭代器

0 阅读1分钟

迭代器

在js中,迭代器是一个具体的对象,这个对象要符合迭代器协议:

  • 迭代器协议定义了产生一系列值(无论是优先还是无限个)的标准方式
  • 有一个特定的next方法,next方法有如下要求:
    • 一个无参数函数,返回一个应当拥有以下两个属性的对象
    • done: 如果迭代器可以产生序列中的下一个值,则为 false,如果迭代器已将序列迭代完毕,则为 true
    • 迭代器返回的任何 JavaScript 值。done 为 true 时可省略
const friends = ["lilei""kobe""james"]  
  
// 创建一个迭代器,用于迭代friends  
let index = 0  
const friendsIterator = {  
  nextfunction() {  
    if (index < friends.length) {  
      return { donefalsevalue: friends[index++] }  
    } else {  
      return { donetruevalueundefined }  
    }  
  }  
}
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 {  
    nextfunction() {  
      if (index < arr.length) {  
        return { donefalsevalue: arr[index++] }  
      } else {  
        return { donetruevalueundefined }  
      }  
    }  
  }  
}  
  
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 { donefalsevaluethis.friends[index++] }  
        } else {  
          return { donetruevalueundefined }  
        }  
      }  
    }  
  }  
}

// 数组本身是一个可迭代对象  
const names = ["abc""cba""nba"]  
  
// 获取可迭代的函数  
console.log(names[Symbol.iterator]) // [Function: values]  
  
// 调用可迭代函数, 获取到迭代器  
const iterator = names[Symbol.iterator]()  
console.log(iterator.next())