2016-03-15 165 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声明