Guest User

Untitled

a guest
Jun 20th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. ////////////////////////////////////////////////////////////////////////////////////////////////////
  2. // Loops, and stepping through loops one step at a time, triggered by an external event
  3. ////////////////////////////////////////////////////////////////////////////////////////////////////
  4.  
  5. let testArray = [1,2,3,4,5];
  6.  
  7. ////////////////////////////////////////////////////////////////////////////////////////////////////
  8. // FIRST -- a simple while loop, for comparison:
  9. ////////////////////////////////////////////////////////////////////////////////////////////////////
  10. let index = 0;
  11. while (index < 5) {
  12. let element = testArray[index];
  13. console.log(index + ": " + element);
  14.  
  15. // Don't forget to iterate! A while loop makes this more obvious:
  16. index++;
  17. }
  18.  
  19. ////////////////////////////////////////////////////////////////////////////////////////////////////
  20. // VERSION 2 -- Advance the loop in stages
  21.  
  22. // Need a trigger to advance to next step -- in this case, a click:
  23. document.addEventListener("click", stepThroughLoop);
  24.  
  25. ////////////////////////////////////////////////////////////////////////////////////////////////////
  26. ///// 2A: Condition inside stepper function
  27.  
  28. // NOTICE: The code below perfectly mirrors a while loop; just replace the "while" line with the "function" line,
  29. // and the condition would go inside the function (so it will stop running the code after a certain number of iterations)
  30. // (OR: check for the negative condition instead and return to exit the function)
  31. let index = 0;
  32. function stepThroughLoop () {
  33. if (index < 5) {
  34. let element = testArray[index];
  35. console.log(index + ": " + element);
  36.  
  37. index++;
  38. }
  39. }
  40. ////////////////////////////////////////////////////////////////////////////////////////////////////
  41. ///// 2B: No condition; instead of simply iterating, wrap back to the start when end is reached
  42. ///// (modular arithmetic, yay!)
  43.  
  44. // NOTICE: Without a condition, we can cycle through all elements or do infinite looping
  45. let index = 0;
  46. function stepThroughLoop () {
  47. let element = testArray[index];
  48. console.log(index + ": " + element);
  49.  
  50. // When index reaches last element, wrap back to the start; otherwise just increment
  51. index = (index === testArray.length - 1 ? 0 : index + 1);
  52.  
  53. // Or keep an incrementer and use remainder operator, as in:
  54. // incrementer++;
  55. // index = incrementer % testArray.length;
  56. }
Add Comment
Please, Sign In to add comment