我不明白这段代码。
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 中没有这样的构造;
您可以在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/