2014-08-29 20 views
-2

我剛開始學習java腳本幾天。一週我開始使用循環,我有相當困惑,請幫助我。如何在JavaScript中使用循環?

它不顯示X?

<!DOCTYPE html> 
<html> 
<head> 
    <title>JavaScript</title> 
    <script type="text/javascript"> 
    var n,x; 
    n = parseInt(prompt("N", "5")); 

    for(i = 1; i <= n; i++) { 
     for(j = 1; j <= i; j++) { 
     x += j; 
     } 
    } 
    x += "<br/>";  
    </script> 
</head> 

<body> 
    <script type="text/javascript"> 
    document.write("<div class=box>"+x+"</div>") 
    </script> 
</body> 
</html> 
+6

,什麼是你的問題? – 2014-08-29 05:47:34

+0

如果你想學習他們..在這裏你去:http://www.w3schools.com/js/js_loop_for.asp – 2014-08-29 05:49:24

+0

我可以知道爲什麼嗎? – 2014-08-29 05:56:10

回答

1

有在你的代碼一些錯誤,你工作的例子應該是這個樣子: -

window.onload = function() { 
    var n; 
    var x = 0; 
    n = parseInt(prompt("N", "5")); 
    for (i = 1; i <= n; i++) { 
    for (j = 1; j <= i; j++) { 
      x += j 
      document.getElementById("box1").innerHTML += x + "<br>"; //Append new results to the document 
     } 
    } 
} 

這裏是鏈接到fiddle

一些失誤點是: -

1)你不應該這樣做x+"<br>",這樣,你是把它當作一個字符串類型,但在循環的另一迭代將執行x+=j,因此它會輸出NaN。寫入文件時應分別附加<br>

2)寫作document.write()在HTML裏面似乎有點奇怪,特別是如果你想使用它的ID引用HTML元素,並追加到打印的x所有值,你應該寫在循環,聲明,你的新x

3)您沒有包括在函數內部腳本,其封裝在一個函數並適當調用該函數執行,例如在我的情況,我呼籲它window.onload

+0

此外,總是[使用基數]('mrseelgaigg.com/blog/2008/10/07/the-importance-of-the-javascript-parseint-radix/)與'parseInt'! – 2014-08-29 12:06:43