In my opinion, this JavaScript should work, but it will not work! The loop is never run (it is skipped altogether).
FYI totalPages = 15
for (var i = 1; i >= totalPages; i++) {
pagingOptions += '<option value="' + i + '">' + i + '</option> ';
}
If I change it like this, it works:
for (var i = 1; i < totalPages; i++) {
pagingOptions += '<option value="' + i + '">' + i + '</option> ';
}
What is the problem? The JavaScript will only run the loop if the comparison is "i < totalPages"? Why would this be the case?
The semantics of the for
loop:
for (expression1; expression2; expression3) {
// ...
}
AFTER: // statements
are:
expression1
expression2
and check to see if it's truthy
. If not, skip subsequent code (here, to "AFTER") for
statement expression3
Thus, the middle expression should evaluate to true
when iteration of the loop body should continue. As soon as it's false
— even if it's false
on the very first try — the loop finishes.
Another way to think of it is that it's like:
expression1;
while (expression2) {
// statements
expression3;
}
I think you have your greater than/less than wrong here:
for (var i = 1; i <= totalPages; i++) {
pagingOptions += '<option value="' + i + '">' + i + '</option> ';
}
In my opinion, this should work (for a given definition of working, as we don't know if you want i
to be less than, or less than or equal to totalPages
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.