zoukankan      html  css  js  c++  java
  • [Javascript] Write a Generator Function to Generate the Alphabet / Numbers

    When you need to generate a data set, a generator function is often the correct solution. A generator function is defined with function* and then you yield each result you want out of the function when you call it. Generators pair well with the ... operator inside of Array because they serve as iterators which can be called until all their results are exhausted.

    function* generateAlphabet() {
      let i = "a".charCodeAt(0);
      let end = "z".charCodeAt(0) + 1;
    
      while (i < end) {
        yield String.fromCharCode(i);
        i++;
      }
    }
    
    let alphabet = [...generateAlphabet()];
    
    Array.prototype.fill = function* generateNumber(val) {
      let i = 0;
      while (i < Number(this.length)) {
        yield typeof val === "function" ? val(i) : val;
        i++;
      }
    };
    var numbers = [...new Array(6).fill()];
    console.log(numbers); // [undefined, undefined, undefined, undefined, undefined, undefined]
    var numbers = [...new Array(6).fill(0)];
    console.log(numbers); // [0, 0, 0, 0, 0, 0]
    var numbers = [...new Array(6).fill(i => i * 2)];
    console.log(numbers); //[0, 2, 4, 6, 8, 10]
  • 相关阅读:
    python实现对单机游戏内存修改
    python_turtle模板画图
    Android向Rest服务Post数据遇到的Date类型数据问题
    Jquery根据字段内容设置字段宽度
    LLVM安装
    impala编译
    JS一些简单的问题
    小三角形的制作方法
    js中的一些简单问题
    另一部分页面
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10311672.html
Copyright © 2011-2022 走看看