我正在完成一本名为“DOM脚本 - 使用JavaScript和文档对象模型进行Web设计”的书,由Jeremy Keith编写。
以下是'do...while'
示例:
var count = 1;
do {
console.log(count);
count++;
} while (count < 11);
在书中他曾说过,如果我们看一下我们的do...while
循环示例,我们可以像这样完整地制定它:
initialize;
while (condition) {
statements;
increment;
}
这肯定是一个错误,这实际上是while
循环而不是do...while
循环的制定。
我还检查了勘误表,看看这是否是书中的错误,但没有提及它。
我是否正确地说这是while
循环而不是do...while
循环的公式?我可以咨询一些权威的ECMAScript文档吗?
答案 0 :(得分:0)
在上面提到的那本书中,do-while被描述为:
As with the if statement, it is possible that the statements contained within the curly
braces of a while loop may never be executed. If the condition evaluates as false on the
first loop, then the code won’t be executed even once.
There are times when you will want the code contained within a loop to be executed at
least once. In this case, it’s best to use a do loop. This is the syntax for a do loop:
do {
statements;
} while (condition);
This is very similar to the syntax for a regular while loop, but with a subtle difference. Even
if the condition evaluates as false on the very first loop, the statements contained within
the curly braces will still be executed once.
因此,在阅读本节后,作者从未说过do-while和while是相同的。他说的是,无论你在做什么,你都可以使用do-while做同样的事情。但是,有一段时间,如果条件在第一次迭代过程中评估为false,它甚至不会进入循环。但是在do-while中,由于语法中的迭代是稍后指定的,因此它将至少进入一次循环。这就是他的意思。