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]
  • 相关阅读:
    XML 的学习笔记3
    XML 的学习笔记2
    XML 的学习笔记1
    Tomcat 学习笔记2
    Tomcat 学习笔记1
    sol
    sol
    0、安装Ionic2
    ionic2 目录
    6、Angular Route 路由
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10311672.html
Copyright © 2011-2022 走看看