在循环javascript中声明变量

时间:2016-03-15 11:25:30

标签: javascript function while-loop scope

我不明白这段代码。

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 个答案:

答案 0 :(得分:5)

您无法在while循环中定义变量,javascript中没有此类构造;

enter image description here

可以在for循环中定义它的原因是因为for循环定义了一个初始化结构。

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

基本上,它不起作用,因为它是无效的代码。

但是,您可以完全删除var声明,但这实际上会使变量global被视为不良做法。

这就是您在var循环正上方看到while声明的原因

相关问题