• generator


    我的github源码:https://github.com/shangyueyue/ssy-utils/blob/master/src/basetheory/generator.js

    一、实现迭代器

    function read(books) {
      let index = 0;
      return {
        next() {
          const done = index === books.length;
          const value = done ? undefined : books[index++]; // eslint-disable-line
          return {
            value,
            done,
          };
        },
      };
    }
    const it = read(['nodejs', 'css', 'js']);
    let result;
    do {
      result = it.next();
      console.log(result);
    } while (!result.done);

    二、gennerator 迭代

    function* func(subjects) {
      let result;
      for (const item of subjects) {
        result = yield item;
        console.log(result);
      }
    }
    const subjects = ['js', 'html5', 'css'];
    const iterater = func(subjects);
    console.log(iterater.next());
    console.log(iterater.next(9));
    console.log(iterater.next(0));

    三、递归遍历

    function* flat(arr) {
      for (const item of arr) {
        if (Array.isArray(item)) {
          yield* flat(item);
        } else {
          yield item;
        }
      }
    }
    const arr = [1, [[2, 3], 4], [5, 6]];
    const iterator = flat(arr);
    let result;
    do {
      result = iterator.next();
      console.log(result);
    } while (!result.done);

    三、symbal iterator 遍历

    function* arrGenerator() {
      for (let i = 0; i < this.length; i++) {
        yield this[i] + 5;
      }
    }
    const arr = [1, 3, 4, 5];
    arr[Symbol.iterator] = arrGenerator;
    // const iterator = arrGenerator(arr);
    for (const item of arr) {
      console.log(item);
    }
    
    实现对象的 for of
    
    function* objGenerator() {
      for (const item of Object.keys(this)) {
        const key = item;
        const value = this[item];
        yield [key, value];
      }
    }
    
    const obj = {
      name: 'shangyueyue',
      age: 18,
    };
    obj[Symbol.iterator] = objGenerator;
    for (const [key, value] of obj) {
      console.log(key, value);
    }
  • 相关阅读:
    iOS 日历控件
    iOS签发者无效
    Swift3
    GitHub管理代码-随笔
    iOS10 适配问题-Xcode8
    iOS 性能调试
    bug
    贝塞尔曲线(UIBezierPath)属性、方法汇总
    webView 自适应高度 document.body 属性
    iOS-集成支付宝支付、微信支付简单总结
  • 原文地址:https://www.cnblogs.com/shangyueyue/p/10873680.html
Copyright © 2020-2023  润新知