do-while语句[重复]

问题描述 投票:8回答:6

可能的重复。 什么时候适合使用do-while?

谁能告诉我这两个语句之间有什么区别,什么时候应该用一个而不是另一个?

var counterOne = -1;

do {
    counterOne++;
    document.write(counterOne);
} while(counterOne < 10);

或者。

var counterTwo = -1;

while(counterTwo < 10) {
    counterTwo++;
    document.write(counterTwo);
}

http:/fiddle.jshell.netShazg6JS4

在这个时候,我不明白为什么会有这样的事情发生 do 语句,如果可以不用在 while 声明。

javascript do-while
6个回答
24
投票

Do While VS While是什么时候检查条件的问题。

一个while循环检查条件,然后执行循环。而DoWhile是先执行循环,然后检查条件。

例如,如果 counterTwo 变量为10或更大,那么dowhile循环将执行一次,而普通的while循环将不执行循环。


9
投票

循环中的 do-while 保证至少运行一次。虽然 while 循环可能根本不会运行。


1
投票

do语句通常确保你的代码至少被执行一次(表达式在最后被评估),而while则在开始时被评估。


1
投票

假设你想在循环中至少处理一次代码块,不管条件如何。


1
投票

do while 在块运行后检查条件。while 在运行之前检查条件。这通常用于代码总是至少运行一次的情况。


1
投票

如果你想把 counterTwo 的值作为另一个函数的返回值,你会在第一种情况下使用 if 语句。

例如

var counterTwo = something.length; 

while(counterTwo > 0) {
    counterTwo--;
    document.write(something.get(counterTwo));
}

var counterTwo = something.length; 

if(counterTwo < 0) return;

do
{
        counterTwo--;
    document.write(something.get(counterTwo));
} while(counterTwo > 0);

第一种情况是有用的,如果你在一个现有的数组中处理数据,第二种情况是有用的,如果你 "收集 "数据。

do
{
     a = getdata();
     list.push(a);
} while(a != "i'm the last item");
© www.soinside.com 2019 - 2024. All rights reserved.