#167 JavaScript Loops

This is an article with the notes that I summarized after learning「Introduction To JavaScript」in Codecademy.

Loops

Loops let us tell the computer to loop over a block of code so that we don't have to write out the same process over and over.

Loops are especially useful when we have an array where we'd like to do something to each of its items, like logging each item to the console. There are two kinds of loops.

  1. for loops, which let us loop a block of code a known amount of times. In the example below, let i = 0 is the starting index, i is the condition, if this condition is true, then i++ will run. Overall it loops through each element in the list favoriteFood, and logs a sentence into the console in each loop.
let favoriteFood = ['donut', 'tofu', 'orange'];

for (let i = 0; i
  1. while loops, which let us loop a block of code an unknown amount of times.
let cards = ['Diamond', 'Spade', 'Heart', 'Club'];
let currentCard = 'Heart';

while (currentCard !== 'Spade') {
  // if currentCard is not Spade, then logs currentCard
  console.log(currentCard);
  // assign a random card from cards to currentCard
  currentCard = cards[Math.floor(Math.random() * 4)];
}

// while loop will stop when it currentCard is Spade
// and then logs the following result into the console
console.log("The program found a spade.");
// because currentCard is selected randomly
// there are no specific outputs
for Loops backwards
let favoriteFood = ['donut', 'tofu', 'orange'];

for (let i = favoriteFood.length - 1; i >= 0; i--) {
  console.log("My favorite food is " + favoriteFood[i]);
}

// The expected outputs:
// My favorite food is orange
// My favorite food is tofu
// My favorite food is donut
Nested for Loops

If you and your friend want to go on a vacation together, you've both made arrays of your favorite places and you want to compare to see if any of them match.

let myPlaces = ['Shanghai', 'Sanya', 'Paris'];
let friendPlaces = ['Shanghai', 'Beijing', 'Guangzhou'];

// the loop starts from Shanghai in myPlaces
// in the next nested for loop
// Shanghai is compared to each element in friendPlaces 
// myIndex will only increase by one when the nested for loop
// has looped through all items in friendPlaces
for (let myIndex = 0; myIndex < myPlaces.length; myIndex++) {
  for (let friendIndex = 0; friendIndex < friendPlaces.length; friendIndex++) {
    if (myPlaces[myIndex] === friendPlaces[friendIndex]) {
      console.log("You have " + friendPlaces[friendIndex] + " in common.");
    }
  }
}

你可能感兴趣的:(#167 JavaScript Loops)