简体   繁体   English

如何在每列增加1的情况下连续循环,依此类推

[英]how to loop in a row with each column increasing by 1 and so on

I have homework to make a program to display several data with the following display: 我有一个家庭作业,使一个程序可以显示以下显示的多个数据:

#
#$
#$%
#$%#
#$%#$
#$%#$%

I had tried, but it looks so weird, I don't know what else to do, I'm stuck, this is my code : 我尝试过,但是看起来很奇怪,我不知道该怎么办,我被卡住了,这是我的代码:

 let str = ''; for (let i = 0; i < 6; i++) { str += '#'; for (let j = 0; j < i; j++) { str += '$'; for (let k = 1; k < i; k++) { str += '%'; for (let k = 1; k < i; k++) { str += '#'; } } } str += backpace = '\\n'; } console.log(str); 

my code does not display what I expect, I hope sombody can help me 我的代码未显示我的期望,希望有人能帮助我

You just need two loops, one for the rows, and one for the columns. 您只需要两个循环,一个循环用于行,一个循环用于列。 The loop for the columns only has to iterate to the current row number, eg for the third row, the column loop has to iterate three times. 列的循环仅需迭代到当前行号,例如,对于第三行,列的循环必须迭代3次。

  for(let col = 0; col <= row; col++)

To get the character to be displayed at a certain column you could take a string of the characters to repeatedly display, eg "#$%" , then access the col-th character in that string. 要使该字符显示在某个列上,您可以使用一串字符重复显示,例如"#$%" ,然后访问该字符串中的第col个字符。 With the modulo operator you can then make sure that col 3 results in the first char to be taken, col 4 the second and so on: 然后,使用模运算符可以确保col 3导致要提取第一个字符,col 4导致第二个字符,依此类推:

 "#$%"[col % 3] // 0 => "#", 1 => "$", 2 => "%", 3 => "#", ...

Way too many loops, you only need 2 loops 循环太多,您只需要2个循环

  let dict = ["#", "$", "%"]; // available symbols in order let str = ''; // final string let linesToRender = 6; // number of lines to render for (let line = 0; line < linesToRender ; line++) { // line loop for (let col = 0; col <= line; col++) { // column loop ( from 0 to line number ) str += dict[col % dict.length] } str += "\\n"; } console.log(str); 

Ok here's your homework. 好的,这是您的作业。 Do not use that many loops, it is not necessary. 不要使用那么多循环,这是没有必要的。 Just store the current line and concat next char in next loopcycle. 只需存储当前行并在下一个循环中连接下一个字符。

 const source = '#$%'; let str = ''; let output = ''; for (let i = 0; i < 6; i++) { str += source[i % source.length]; output += str + '\\n'; } console.log(output); 

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

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