TIL - Javascript - for, while loops

홍예찬·2020년 7월 29일
0
post-thumbnail
post-custom-banner

1. for loops

  • false = stop condition
for (let counter = 5; counter < 11; counter++ ) {
  console.log(counter);
}
//Output:5 6 7 8 9 10

2. for loops in reverse

for (let counterTwo = 3; counterTwo >= 0; counterTwo--){
  console.log(counterTwo);
}
//Output:3  2  1  0

3. for loops through arrays

const vacationSpots = ['Bali', 'Paris', 'Tulum'];

for (let i =0; i < vacationSpots.length; i++){
  console.log('I would love to visit ' + vacationSpots[i]);
}
/*Output:
I would love to visit Bali
I would love to visit Paris
I would love to visit Tulum
*/

4. for loops(Nested)

let bobsFollowers = ['Joe', 'Marta', 'Sam', 'Erin'];
let tinasFollowers = ['Sam', 'Marta', 'Elle'];
let mutualFollowers = [];

for (let i = 0; i < bobsFollowers.length; i++) 
  { for (let j = 0; j < tinasFollowers.length; j++) 
    { if (bobsFollowers[i] === tinasFollowers[j]) 
      { mutualFollowers.push(bobsFollowers[i]);
    }
  }
};
const name = mutualFollowers;
console.log(name); 
//또는
console.log(mutualFollowers);
//Output: [ 'Marta', 'Sam' ]

5. while loops

  • 결정되지 않은 횟수를 실행할 때 while을 사용
const cards = ['diamond', 'spade', 'heart', 'club'];

let currentCard;

while ( currentCard != 'spade') {
  currentCard = cards[Math.floor(Math.random() * 4)];
console.log(currentCard);
}
//Output: random

6. Do While Statements

  • while은 먼저 조건을 비교한 후에 내용을 실행
  • do while은 내용을 먼저 실행한 후 조건을 비교(내용이 최소 1번은 실행됨)
let cupsOfSugarNeeded = 3;
let cupsAdded = 0;

do {
  cupsAdded++ ;
} while(cupsAdded < cupsOfSugarNeeded);

console.log(cupsAdded);
//Output: 3

7. The break keyword

const rapperArray = 
      ["Lil' Kim", "Jay-Z", "Notorious B.I.G.", "Tupac"];

for (let i = 0; i < rapperArray.length; i++){
  console.log(rapperArray[i]);
  if (rapperArray[i] === "Notorious B.I.G."){
    break;
  }
}

console.log("And if you don't know, now you know.");
/*Output:
Lil' Kim
Jay-Z
Notorious B.I.G.
And if you don't know, now you know.
*/
profile
내실 있는 프론트엔드 개발자가 되기 위해 오늘도 최선을 다하고 있습니다.
post-custom-banner

0개의 댓글