2016-03-15 162 views
0

我不明白這段代碼。while循環中聲明變量javascript

var timesTable; 
while ((timesTable = prompt("Enter the times table", -1)) != -1) {.....} 

爲什麼有必要先聲明變量?我試圖做到這一點:

while ((var timesTable = prompt("Enter the times table", -1)) != -1) {.....} 

但它不起作用。有什麼問題?是關於範圍的東西?

完整的程序是:通過提前

function writeTimesTable(timesTable, timesByStart, timesByEnd) { 
     for (; timesByStart <= timesByEnd; timesByStart++) { 
      document.write(timesTable + " * " + timesByStart + " = " + timesByStart * timesTable + "<br />"); 
      } 
     } 
    var timesTable; 
    while ((timesTable = prompt("Enter the times table", -1)) != -1) { 
     while (isNaN(timesTable) == true) { 
      timesTable = prompt(timesTable + " is not a " + "valid number, please retry", -1); 
     } 
     document.write("<br />The " + timesTable + " times table<br />"); 
     writeTimesTable(timesTable, 1, 12); 
    } 

感謝。

+1

定義的原因「不工作」。 – deceze

回答

5

你不能在一個while循環中定義一個變量,在javascript中沒有這樣的構造;

enter image description here

,你可以一個循環for內定義它的原因是因爲一個for循環定義了一個初始化結構。

for (var i = 0; i < l; i++) { ... } 
//  |   |  | 
// initialisation |  | 
//   condition | 
//     execute after each loop 

基本上,它不會工作,因爲它是無效的代碼。

但是,您可以完全刪除var聲明,但實質上會使變量global被認爲是不好的做法。

這就是你直接看到while環以上的var聲明