2013-03-14 88 views
0

我想在JavaScript中輸出這樣的內容。在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> 

肯定這個代碼不工作,我需要的方式to..I感到困惑的我怎麼能在我要求的方式打印* ...

+0

新線路爲 「
」 – QuentinUK 2013-03-14 22:37:35

+2

看多久你的內循環運行。看看你在哪裏打印換行符。再想一想。 – 2013-03-14 22:38:17

回答

2

變化內環到

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... 
+0

毫無疑問,它工作正常,更像CS101 – 2013-03-14 22:46:46

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)); 
+0

完美的作品...但它更像CS201,我只記得那些日子,我記得老師做了這個例子,但現在,我無法做到這一點,謝謝 – 2013-03-14 22:44:03

+0

如何你這樣做可能取決於本課的目的是教授嵌套循環還是替代邏輯。 ;-) – RobG 2013-03-14 23:58:36

+0

是真實的,我沒有想到嵌​​套循環或替代邏輯,幾年前,當我嘗試創建這個例子時,我記起了我的大學生活,thanka指導 – 2013-03-15 00:10:23