Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- // Loops, and stepping through loops one step at a time, triggered by an external event
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- let testArray = [1,2,3,4,5];
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- // FIRST -- a simple while loop, for comparison:
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- let index = 0;
- while (index < 5) {
- let element = testArray[index];
- console.log(index + ": " + element);
- // Don't forget to iterate! A while loop makes this more obvious:
- index++;
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- // VERSION 2 -- Advance the loop in stages
- // Need a trigger to advance to next step -- in this case, a click:
- document.addEventListener("click", stepThroughLoop);
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- ///// 2A: Condition inside stepper function
- // NOTICE: The code below perfectly mirrors a while loop; just replace the "while" line with the "function" line,
- // and the condition would go inside the function (so it will stop running the code after a certain number of iterations)
- // (OR: check for the negative condition instead and return to exit the function)
- let index = 0;
- function stepThroughLoop () {
- if (index < 5) {
- let element = testArray[index];
- console.log(index + ": " + element);
- index++;
- }
- }
- ////////////////////////////////////////////////////////////////////////////////////////////////////
- ///// 2B: No condition; instead of simply iterating, wrap back to the start when end is reached
- ///// (modular arithmetic, yay!)
- // NOTICE: Without a condition, we can cycle through all elements or do infinite looping
- let index = 0;
- function stepThroughLoop () {
- let element = testArray[index];
- console.log(index + ": " + element);
- // When index reaches last element, wrap back to the start; otherwise just increment
- index = (index === testArray.length - 1 ? 0 : index + 1);
- // Or keep an incrementer and use remainder operator, as in:
- // incrementer++;
- // index = incrementer % testArray.length;
- }
Add Comment
Please, Sign In to add comment