在JavaScript中打印二维

Printing two dimensional in JavaScript

本文关键字:二维 JavaScript 打印      更新时间:2023-09-26

我想在JavaScript中输出这样的东西。

*
**
***
****
*****

I am trying

<script type="text/javascript" language="javascript">
var i ,j ;
for(i=1;i<=6;i++){
  for(j=1;j<=6;j++){
    document.write('*');    
    document.write('<br>');    
  }
  document.write('<br>');   
}
</script>

绝对这段代码不工作的方式,我需要它…我很困惑,我如何才能打印*在我需要的方式…

将内循环改为

for (j=1; j<=i; j++) {
             ^---  the important bit
    document.write('*');
}
document.write('<br>');

这样,内循环打印*字符的i值,当你完成6行时,外循环负责停止事情。例如

i | j     | printed
-------------------
1 | 1     | *
2 | 1,2   | **
3 | 1,2,3 | ***
etc...

你只需要一个循环:

function writeStars(n) {
    var m = '',
        t = [];
    for (var i=0; i<n; i++) {
      m += '*';
      t.push(m);
    }
    return t.join('<br>') + '<br>';
}
document.write(writeStars(6));