javascript - 在 while 循环内声明变量 javascript

标签 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);
    }

提前致谢。

最佳答案

您不能在 while 循环中定义变量,JavaScript 中没有这样的构造;

enter image description here

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

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

基本上,它不会工作,因为它是无效代码。

但是,您可以完全删除 var 声明,但这实际上会使变量全局,并且被认为是不好的做法。

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

关于javascript - 在 while 循环内声明变量 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36009945/

相关文章:

c - 实际在 C 中定义的函数的 undefined reference 错误

python - 我的主要功能是无限循环重复,我不知道为什么

linux - bash:一次从字符串中读取一个字符

java - 在 Java 中使用 boolean 方法的循环程序

javascript - 调用preventDefault()后无法调用submit()

javascript - 尝试动态更改 anchor HREF

javascript - 错误: Uncaught TypeError: undefined is not a function

c - 如果用户没有输入正确的值,使 C 程序返回开始并再次要求输入

javascript - knockout ,嵌套foreach

javascript - 防止JS定时器溢出