1. for loops
for (let counter = 5; counter < 11; counter++ ) {
console.log(counter);
}
2. for loops in reverse
for (let counterTwo = 3; counterTwo >= 0; counterTwo--){
console.log(counterTwo);
}
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]);
}
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);
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);
}
6. Do While Statements
- while은 먼저 조건을 비교한 후에 내용을 실행
- do while은 내용을 먼저 실행한 후 조건을 비교(내용이 최소 1번은 실행됨)
let cupsOfSugarNeeded = 3;
let cupsAdded = 0;
do {
cupsAdded++ ;
} while(cupsAdded < cupsOfSugarNeeded);
console.log(cupsAdded);
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.");