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.
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.
Share Improve this question asked Mar 15, 2016 at 11:25 guillemusguillemus 1013 silver badges11 bronze badges 1- 1 Define "doesn't work". – deceze ♦ Commented Mar 15, 2016 at 11:27
2 Answers
Reset to default 7You can't define a variable within a while
loop, there is no such construct in javascript;
The reason that you can define it within a for
loop is because a for loop has an initialization construct defined.
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 pletely, but that will essentially make the variable global
and is considered bad practice.
That is the reason you are seeing the var
declaration directly above the while
loop
This is the best alternative I could e up with
for (let i = 0; i < Number.MAX_VALUE; i++) {
const variable = getVariable(i);
if (/* some condition */) { break; }
/* logic for current iteration */
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744843169a4596680.html
评论列表(0条)