0

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

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

我在尝试

<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>

绝对这段代码不能按我需要的方式工作..我对如何*以我需要的方式打印感到困惑...

4

2 回答 2

2

将内循环更改为

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

这样,内循环会打印出多达6 行i*字符,而外循环会负责在完成 6 行后停止处理。例如

i | j     | printed
-------------------
1 | 1     | *
2 | 1,2   | **
3 | 1,2,3 | ***
etc...
于 2013-03-14T22:38:07.277 回答
2

你只需要一个循环:

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));
于 2013-03-14T22:41:59.300 回答