Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 1st, 2012  |  syntax: None  |  size: 1.50 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Is the break keyword in Javascript only meant for breaking out of loops?
  2. funProgram: for(;;) {
  3.   numberGuesser: {
  4.     var num = (Math.random() * 100) | 0;
  5.     var guess = +prompt("I'm thinking of a number between 0 and 100. Try to guess it.", 0);
  6.     var guesses = 1;
  7.     guess: for(;;) {
  8.       higher: {
  9.         lower: {
  10.           if(guess === num) break guess;
  11.           if(guess > num) break lower;
  12.           guess = +prompt("Too low. Try again.", 0);
  13.           break higher;
  14.         }
  15.         guess = +prompt("Too high. Try again.", 0);
  16.       }
  17.       guesses++;
  18.     }
  19.     alert("You got it in " + guesses + " guesses! The number is " + num);
  20.   }
  21.   var again = prompt("Do you want to guess again (y/n)?", "y") === "y";
  22.   if(!again) break funProgram;
  23. }
  24.        
  25. for (;;){ // "for a"
  26.   for(;;){ // "for b"
  27.     break; // breaks "for b"
  28.   }
  29. }
  30.        
  31. myblock: {
  32.   for(;;){
  33.     for(;;){
  34.       break mybock; // breaks label "myblock"
  35.     }
  36.   }
  37. }
  38.        
  39. function myblock(){
  40.   for(;;){
  41.     for(;;){
  42.       return; // exits function "myblock"
  43.     }
  44.   }
  45. }
  46.        
  47. var again = true;
  48. while (again){
  49.     var num = (new Date()).getMilliseconds() % 100,
  50.         guess = +prompt("I'm thinking of a number between 0 and 100. Try to guess it.", "1"),
  51.         guesses = 1;
  52.     while (num !== guess){
  53.         guesses++;
  54.         guess = +prompt((guess < num ? "Too low." : "Too high.") + " Try again.", guess);
  55.     }
  56.     alert("You got it in " + guesses + " guesses! The number is " + num);
  57.     again = prompt("Do you want to guess again? (y/n)", "y") == "y";
  58. }