自己实现一个简易的iterator

1.数组和字符串的迭代器iterator

const arr = [1, 2, 3, 4];
const str = "hello";
function myIterator(arr) {
  let index = 0;
  return {
    next() {
      if (index < arr.length) {
        return {
          value: arr[index++],
          done: false,
        };
      }
      return { value: undefined, done: true };
    },
  };
}
let iter = myIterator(arr);
console.log(iter.next()); // {value: 1, done: false}
console.log(iter.next()); // {value: 2, done: false}
console.log(iter.next()); // {value: 3, done: false}
console.log(iter.next()); // {value: 4, done: false}
console.log(iter.next()); // {value: undefined, done: true}
let iter1 = myIterator(str);
console.log(iter1.next()); // {value: 'h', done: false}
console.log(iter1.next()); // {value: 'e', done: false}
console.log(iter1.next()); // {value: 'l', done: false}
console.log(iter1.next()); // {value: 'l', done: false}
console.log(iter1.next()); // {value: 'o', done: false}
console.log(iter1.next()); // {value: undefined, done: true}

 

2.自定义实现对象迭代

let obj = {
  a: 1,
  b: 2,
  c: 3,
  [Symbol.iterator]() {
    let index = 0;
    let map = new Map();
    map.set('a', 1);
    map.set('b', 2);
    map.set('c', 3);
    return {
      next() {
        let mapEntries = [...map.entries()];
        if(index < map.size) {
          return {
            value: mapEntries[index++],
            done: false
          };
        }
        return {value: undefined, done: true};
      }
    }
  }
}
let iter = obj[Symbol.iterator]();
console.log(iter.next());// {value: ['a', 1], done: false}
console.log(iter.next());// {value: ['b', 2], done: false}
console.log(iter.next());// {value: ['c', 3], done: false}
console.log(iter.next());// {value: undefined, done: true}

使用for of其实是调用了[Symbol.iterator]这个迭代器方法,如果没有这个方法就没法使用for of来遍历了。

 

 3.遍历和迭代有什么区别
 从目标源依次逐个抽取的方法来提取数据
 目标源满足的要求有: 1.有序的(基于index索引) 2.连续的
 遍历没有严格要求,属于比较笼统的说法
 
4.哪些数据类型有迭代器方法,可以通过for of遍历
Array, Map, Set, String, TypeArray, arguments, NodeList
posted @ 2021-10-21 16:44  jerryfish  阅读(91)  评论(0编辑  收藏  举报