如何根据字母表制作金字塔?

时间:2017-10-20 08:44:27

标签: javascript alphabet

那么如何制作多个字母呢?我正在使用带字符串的数组,我希望将它们乘以索引。

A
BB
CCC
DDDD
EEEEE 

<script>
    window.onload = start;
    var letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", 
                   "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
    var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 
                   21, 22, 23, 24, 25, 26];

    function start() {
        document.getElementById("randomize").onclick = execute;
    }

    function execute() {
        for (var i = 0; i < letters.length; i++) {
            for (var j = 0; j <= numbers.length; j++) {
                var product = numbers.length * letters[i];
                document.getElementById("output").innerHTML += "<li>" + letters[i] + "</li>";
            }
        }
    }
</script>

3 个答案:

答案 0 :(得分:5)

for(var i = 0; i < 26; i++){
    console.log(String.fromCharCode(65 + i).repeat(i + 1));
}

给你

A
BB
CCC
...

更短的一个:

var i = 0;
while(i++ < 26) console.log(String.fromCharCode(64 + i).repeat(i));

答案 1 :(得分:2)

你做的几乎一切都很完美,除了你需要得到numbers[i]值而不是长度。

&#13;
&#13;
window.onload = start;

var letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", 
               "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
               21, 22, 23, 24, 25, 26];

function start() {
  document.getElementById("randomize").onclick = execute;
}


function execute() {
  for (var i = 0; i < letters.length; i++) {
    var product = "";
    for (var j = 0; j < numbers[i]; j++)
      product += letters[i];
    document.getElementById("output").innerHTML += "<li>" + product + "</li>";
  }
}
&#13;
li {font-family: 'Consolas', monospace;}
&#13;
<button id="randomize">Randomize</button>
<div id="output"></div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

在一个oneliner(somewhath):

document.getElementById("output").innerHTML = "<li>" + 
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("").map(
         x => "".padStart(x.charCodeAt(0) - "A".charCodeAt(0) + 1, x)
    ).join("</li>\n<li>") + "</li>"

其中:

  • "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("")从字符串
  • 创建数组
  • x => "".padStart(x.charCodeAt(0) - "A".charCodeAt(0) + 1, x)为字符x
  • 创建字符串
  • padStart创建一个具有所需长度的字符串
  • 长度取决于他在字母x.charCodeAt(0) - "A".charCodeAt(0) + 1中的位置,请参阅String.charCodeAt
  • 外部联接创建包含计算字符串的列表