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]
  • 相关阅读:
    HttpClient
    充值保存
    button 样式
    创建窗口
    第十一次作业
    第十次作业
    第九次作业
    第八次作业
    第七次作业
    第六次作业
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10311672.html
Copyright © 2011-2022 走看看