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]
  • 相关阅读:
    Xaml下
    Xmal
    ItemTemplate
    spring aop
    Struts2
    jsp的标签库
    数据库连接池
    request初探
    kubectl 命令大全
    win10常见问题归总
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10311672.html
Copyright © 2011-2022 走看看