Do...while和while...do的区别在于对于临界值的测试上。当在执行的时候只选择临界值来测试时,你会发现do...while至少要执行一次,而while...do则一次都不会执行。但是,当不去考虑临界值的时候,do...while和while...do的执行结果是一样的。让我们用事实来说话吧:
只测试临界值:
1 <!DOCTYPE html> 2 <html> 3 <body> 4 <p>Try to practice while statement!</p> 5 <p id = "demo"></p> 6 <script> 7 var x = ""; 8 var i = 0; 9 var x = ""; 10 var i = 0; 11 while(i < 0) 12 { 13 x += "The number is " + i + "." + "<br>"; 14 i ++; 15 document.getElementById("demo").innerHTML = x; 16 } 17 18 do 19 { 20 x +="The number is " + i + "." + "<br>"; 21 i++; 22 document.getElementById("demo").innerHTML = x; 23 } 24 while(i < 0); 25 </script> 26 </body> 27 </html>
尝试着只去测试临界值(i=0)时,你会发现只有do...while会输出,而while...do会在判断时直接不符合条件,这似乎很简单的逻辑,但有时候,也会让死钻牛角尖的我陷入混乱的状态。
不考虑临界值时只执行while语句:
1 <!DOCTYPE html> 2 <html> 3 <body> 4 <p>Try to practice while statement!</p> 5 <p id = "demo"></p> 6 <script> 7 var x = ""; 8 var i = 0; 9 while(i < 5) 10 { 11 x += "The number is " + i + "." + "<br>"; 12 i ++; 13 document.getElementById("demo").innerHTML = x; 14 } 15 </script> 16 </body> 17 </html>
不考虑临界值时只执行do...while语句:
1 <!DOCTYPE html> 2 <html> 3 <body> 4 <p>Try to practice do while statement!</p> 5 <p id = "demo"></p> 6 <script> 7 var x = ""; 8 var i = 0; 9 do 10 { 11 x +="The number is " + i + "." + "<br>"; 12 i++; 13 document.getElementById("demo").innerHTML = x; 14 } 15 while(i < 5); 16 </script> 17 </body> 18 </html>
你会发现此时他们的执行结果是一样的。所以在使用的时候不用再纠结是选哪种循环来执行。
说明:我目前所学习的所有例子都是来自于 http://www.w3schools.com.