简体   繁体   English

使用FOR循环在每次循环迭代中添加其他字符或符号

[英]Use FOR loop to add additional characters or symbols each loop iteration

Using a FOR loop to add and output numbers is easy. 使用FOR循环添加和输出数字很容易。 But how do you add and output additional characters? 但是,如何添加和输出其他字符?

For example the following simple program outputs the numbers 1 through 7 to the console . 例如,以下简单程序将数字1到7输出到console

for (var count = 0; count < 7; count++) {
    console.log(count + 1);
}

But what if instead of numbers I needed to add additional characters or symbols each loop? 但是,如果需要在每个循环中添加其他字符或符号来代替数字,该怎么办? For example how would someone output characters to the console like this? 例如,有人将这样向console输出字符吗?

A 一种

AA 机管局

AAA AAA级

AAAA AAAA

AAAAA AAAAA

AAAAAA AAAAAA

AAAAAAA AAAAAAA

I'm sure the answer is straightforward but I don't know how to approach this type of problem. 我敢肯定答案很简单,但是我不知道如何解决这类问题。

It is rather easy. 这很容易。

for (var count = 0; count < 7; count++) {
    switch (count) {
        case 7: console.log('AAAAAAA'); break;
        case 6: console.log('AAAAAA'); break;
        case 5: console.log('AAAAA'); break;
        case 4: console.log('AAAA'); break;
        case 3: console.log('AAA'); break;
        case 2: console.log('AA'); break;
        case 1: console.log('A'); break;
        case 0: console.log('xd'); break;
    }
}

Okay... jokes aside. 好吧...开个玩笑。

But for real: 但实际上:

for (var count = 0; count < 7; count++) {
    console.log(new Array(count + 1).join('A'));
}

Or if you badly want to append: 或者,如果您非常想附加:

for (var str = ""; str.length < 10; str += "A") {
    console.log(str);
}

Simple loop for text appending: 文本附加的简单循环:

var txt = ""; 
for(var count = 0; count < 7; count++) { 
    console.log(txt+="A"); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM