2013-02-19 103 views
2

我在這裏有此代碼..其中變量num是n乘n平方表的維數。目標是輸入一個數字並創建一個以數字爲維度的表格。Javascript:for-loop無法正常工作

我得到了這段代碼,但它並沒有通過for循環的兩層。代碼執行後,字符串* change_text *只需變成:<table></table>

change_text = "<table>"; 

    for (var i; i<num; i++) { 
     change_text = change_text + "<tr>"; 
     for (var j; j<num; j++) { 
      change_text = change_text + "<td> asdf </td>"; 

      //code for blue cells 
     } 
     change_text = change_text + "</tr>"; 
    } 


    change_text = change_text+ "</table>" 
+1

作爲參考,你可以簡單地做'change_text + =「新文本」;'而不是'change_text = change_text +「新文本」;' – 2013-02-19 15:00:18

回答

1

您需要爲您的循環指定起始值:

change_text = "<table>"; 

    for (var i = 0; i<num; i++) { 
     change_text = change_text + "<tr>"; 
     for (var j = 0; j<num; j++) { 
      change_text = change_text + "<td> asdf </td>"; 

      //code for blue cells 
     } 
     change_text = change_text + "</tr>"; 
    } 


    change_text = change_text+ "</table>" 

目前我會假設ijundefined和所以循環不會去任何地方。

1

你需要初始化i和j ... 試試這個:

change_text = "<table>"; 

for (var i=0; i<num; i++) { 
    change_text = change_text + "<tr>"; 
    for (var j=0; j<num; j++) { 
     change_text = change_text + "<td> asdf </td>"; 

     //code for blue cells 
    } 
    change_text = change_text + "</tr>"; 
} 


change_text = change_text+ "</table>" 
3

需要初始化你的迭代器:

for(var i = 0; i < num; i++) 
0

你忘了i=0/j=0初始化。您只聲明瞭變量,並且undefined總是從數字比較中產生false,這些比較立即打破循環。所以,你的代碼更改

change_text = "<table>"; 
for (var i=0; i<num; i++) { 
    change_text = change_text + "<tr>"; 
    for (var j=0; j<num; j++) { 
     change_text = change_text + "<td> asdf </td>"; 
     //code for blue cells 
    } 
    change_text = change_text + "</tr>"; 
} 
change_text = change_text+ "</table>" 
1

需要初始化i和j,就像這樣:

for (var i = 0; i<num; i++) 
1

未初始化我,讓我= 0

for (var i=0; i<num; i++) { 
     //code 
    }