0

我正在完成 Jeremy Keith 编写的名为“DOM 脚本 - 使用 JavaScript 和文档对象模型的网页设计”的书。

这是'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 文档?

4

1 回答 1

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 是相同的。他说的是,无论你在做什么使用 while,你都可以使用 do-while 来做同样的事情。但是,在一段时间内,如果在第一次迭代本身期间条件评估为假,它甚至不会进入循环。但是在do-while中,由于语法中的迭代是后面指定的,所以它至少会进入循环一次。他的意思差不多就是这个。

于 2013-01-16T12:22:28.933 回答