zoukankan      html  css  js  c++  java
  • JavaScript 算法 1_3 生成器函数实现迭代功能

    JavaScript 算法 1_3 生成器函数实现迭代功能

    以算法 1_1 为例


    类定义

    // 类定义
    class Stack{
      constructor() {
        // 栈顶元素, 包括 next 和 ele
        this.first = null;
        this.count = 0;
      }
      isEmpty(){
        return this.count === 0;
      }
      size(){
        return this.count;
      }
      push(item){
        let oldFirst = this.first;
        let next = {};
        Object.assign(next, {ele: null, next: null});
        next.ele = item;
        this.first = next;
        this.first.next = oldFirst;
        this.count++;
      }
      pop(){
        let top = this.first.ele;
        this.first = this.first.next;
        this.count--;
        return top;
      }
      // 注意这个位置
      *[Symbol.iterator](){
        let index = this.first;
        while (!!index){
          yield index;
          index = index.next;
        }
      }
    }
    

    注意最后一个函数 *[Symbol.iterator], 这个函数实现了默认迭代器的功能, * 是generator 函数声明

    有了这个函数后, 该类可以使用 for of , ..., 等遍历每一个节点


    使用方式

    const stack = new Stack();
    
    stack.push(20);
    // console.log(stack);
    stack.push('小歪');
    stack.push([20, 30]);
    stack.push({name: '张三'});
    
    for(let item of stack){
      console.log(item);
    }
    /*
    {
      ele: { name: '张三' },
      next: { ele: [ 20, 30 ], next: { ele: '小歪', next: [Object] } }
    }
    { ele: [ 20, 30 ], next: { ele: '小歪', next: { ele: 20, next: null } } }
    { ele: '小歪', next: { ele: 20, next: null } }
    { ele: 20, next: null }
    */
    

    之后遍历内容就十分的简单了

  • 相关阅读:
    BA 的职责
    How to grow up as a BA
    打开struts-config.xml 报错 解决方法Could not open the editor
    eclipse中svn插件的工程不能与svn资源库同步的解决方法
    三种常用的MySQL建表语句(转)
    MySQL中CURRENT_TIMESTAMP(转)
    JavaWeb之CSS详解
    如何在Mac OSX系统下安装Tomcat
    JavaWeb之XML详解
    JavaWeb之HTML入门及常用标签
  • 原文地址:https://www.cnblogs.com/xiaxiangx/p/14276936.html
Copyright © 2011-2022 走看看