简体   繁体   English

在while循环javascript中声明变量

[英]declaring variable inside while loop javascript

I don't understand this code.我不明白这段代码。

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

Why is necessary to declare the variable before?为什么必须先声明变量? I tried to do this:我试图这样做:

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

but it doesn't work.但它不起作用。 What's the problem?有什么问题? Is something about scope?是关于范围的吗?

The full program is:完整的程序是:

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

Thanks by advance.提前谢谢。

You can't define a variable within a while loop, there is no such construct in javascript;您不能在while循环中定义变量,javascript 中没有这样的构造;

在此处输入图像描述

The reason that you can define it within a for loop is because a for loop has an initialization construct defined.可以for循环中定义它的原因是因为 for 循环定义了一个初始化构造。

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

Basically, it won't work because it is invalid code.基本上,它不起作用,因为它是无效代码。

You can however remove the var declaration completely, but that will essentially make the variable global and is considered bad practice.但是,您可以完全删除var声明,但这基本上会使变量成为global变量,并且被认为是不好的做法。

That is the reason you are seeing the var declaration directly above the while loop这就是您在while循环正上方看到var声明的原因

This is the best alternative I could come up with这是我能想到的最好的选择

for (let i = 0; i < Number.MAX_VALUE; i++) {
  const variable = getVariable(i);
  if (/* some condition */) { break; }
  /* logic for current iteration */
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM