Learn Javascript - "Loops 2"

minjoo kim·2021년 1월 5일
0

Loopd -2

[Nested Loops] - 중첩 루프
루프가 다른 루프 내부에서 실행되는 경우, 이를 중첩 루프라고합니다. 중첩 된 for 루프의 한 가지 용도는 두 배열의 요소를 비교하는 것입니다. 외부 for 루프의 각 라운드에 대해 내부 for 루프가 완전히 실행됩니다.

const myArray = [6, 19, 20];
const yourArray = [19, 81, 2];
for (let i = 0; i < myArray.length; i++) {
  for (let j = 0; j < yourArray.length; j++) {
    if (myArray[i] === yourArray[j]) {
      console.log('Both loops have the number: ' + yourArray[j])
    }
  }
};

이 예제의 중첩 루프에서 무슨 일이 일어나고 있는지 생각해 봅시다. 외부 루프 배열 myArray의 각 요소에 대해 내부 루프는 외부 배열 myArray [i]의 현재 요소를 내부 배열 yourArray [j]의 각 요소와 비교하여 전체적으로 실행됩니다. 일치하는 항목을 찾으면 콘솔에 문자열을 인쇄합니다.

const bobsFollowers = ['Jason', 'Jenny', 'MJ', 'Daniel'];
const tinasFollowers = ['Jason', 'MJ', 'Ringo’];
const 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]);
    }
  }
};

[The While Loop]
서로 다른 종류의 루프 : While 루프
시작하기에 앞서서 for 루프를 while 루프로 변환해보자.

// A for loop that prints 1, 2, and 3
for (let counterOne = 1; counterOne < 4; counterOne++){
  console.log(counterOne);
}
 
// A while loop that prints 1, 2, and 3
let counterTwo = 1;
while (counterTwo < 4) {
  console.log(counterTwo);
  counterTwo++;
}

-루프 전에 선언된 counterTwo 변수!
-CounterTwo 변수는 루프 전에 선언되어(Global scope), while루프 안으로 엑세스 할 수 있습니다.
-while 키워드로 루프를 시작하고 중지 조건 또는 테스트 조건이 이어집니다. 루프 시작전 값이 “true”이면 계속해서 실행되고 “false”이면 멈추게 됩니다.
-콘솔에 인쇄하는 코드 다음으로는 counterTwo를 증가시키는 루프의 코드 블록이 있습니다.

블록내에서 counterTwo를 증가시키지 않으면 첫선언한 값 1로 계속 남아있게 됩니다.
즉, 테스트 조건 counterTwo <4는 항상 참으로 평가되고 루프가 실행을 멈추지 않습니다!
(이것을 ‘무한루프’(infinite loop)라고 하는데, 컴퓨터의 모든 처리 능력을 차지할 수 있으며 잠재적으로 컴퓨터를 멈출 수 있기때문에 피해야 합니다.)

const cards = ['diamond', 'spade', 'heart', 'club'];

// Write your code below

let currentCard;

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

spade가 나올때 까지는 계속 반복(루프) 되는 놀이.
실행값이 계속 달라짐.

diamond
heart
spade
diamond
diamond
diamond
Spade

[Do...While Statements]
경우에 따라 코드를 한 번 초기 실행 후 특정 조건에 따라 반복하기를 원할때는, do ... while 문을 써봅시다!

do ... while 문은 작업을 한 번 수행 한 다음 지정된 조건이 더 이상 충족되지 않을 때까지 계속하도록합니다.

let countString = '';
let i = 0;
 
do {
  countString = countString + i;
  i++;
} while (i < 5);
 
console.log(countString);

코드 블록에서 i변수는 ’string’ 형식을 추가하여, countString변수를 변경.
do키워드 뒤의 코드 블럭이 한 번 실행 + 조건이 ‘참’일시 블록이 다시 실행 -> 거짓일시 루핑 중지.

=> while 루프와 달리 do ... while은 조건이 참인지와 관계없이 한 번 이상 실행됩니다.

[The break Keyword]
작성한 루프 코드가 중지 조건이 충족되지 않더라도, 루프가 실행되지 않도록 하려면, break 키워드를 사용할 수 있습니다.

for (let i = 0; i < 99; i++) {
  if (i > 2 ) {
     break;
  }
  console.log('Banana.');
}
 
console.log('Orange you glad I broke out the loop!');
//output
Banana.
Banana.
Banana.
Orange you glad I broke out the loop!
const rapperArray = ["Lil' Kim", "Jay-Z", "Notorious B.I.G.", "Tupac"];

// Write your code below
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.")

이해도 ⭐️⭐️
i의 사용과, 루프 코드를 작성하는게 많이 헷갈림.

0개의 댓글