while
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>范例5-7</title> </head> <body> <script language="javascript"> var num = 1; while( num < 101 ) { document.write( num + " " ); num++; } </script> </body> </html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>范例5-8</title> </head> <body> <script language="javascript"> var num = 1; do { document.write( num + " " ); num++; } while( num < 101 ) </script> </body> </html>
while ...break
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>范例5-9</title> </head> <body> <script language="javascript"> var time = 0; while( true ) // 无限循环 { time++; var random = Math.floor( Math.random() * (1000) ); // 摇奖,随机产生2位中奖号码 if( random == 352 ) // 这位彩票迷的号为:35 { alert( "恭喜你,偿试了" + time + "遍,终于中了一次奖(号码:352)"); break; } } </script> </body> </html>