[JavaScript] 반복문


반복문이란?

반복적인 코드의 양을 획기적으로 압축

  • 최초식 : let i = 0
  • 조건식 : i < 10
  • 증감문 : i = i + 1


for 문

break를 사용하여 중단하거나, continue를 사용하여 넘겨줄 수 있다.

for (let i = 0; i < 10; i = i + 1) {
  // 반복할 내용
}


while 문

최초식, 조건식, 증감식이 분할되어 사용
while문은 종료 조건을 제대로 설정하지 않으면 무한 반복한다.

let i = 0;
while (i < 10) {
  //  반복할 내용
  i = i + 1;
}
let answer = 0;
let current = 1;

while (current !== 100) {
  current++;
  answer++;
}
console.log(answer);


for-of 문

for-of문은 각각의 요소들을 가져올 수 있다. (문자열, 배열)

const arr = [1, 2, 3, 4, 5];

for (let el of arr) {
  console.log(el);
}

const str = "abcde";

for (let letter of str) {
  console.log(letter);
}


for-in 문

for-in문은 객체를 반복할 수 있다. (문자열, 객체, 배열)
for-of문보다 효율이 떨어진다. (느림)

const obj = {
  name: "otter",
  gender: "male",
};

for (let key in obj) {
  console.log(obj.key);
}

const str = "abcde";

for (let index in str) {
  console.log(str[index]);
}


forEach

forEach문은 배열에서만 사용할 수 있다.
forEach는 for문 처럼 중단할 수 없다.

const arr = ["a", "b", "c", "d", "e"];

arr.forEach((el, i) => {
  console.log(el, i);
});

// forEach문을 중단하려면 아래와 같이 한다.
let able = false;
arr.forEach((el, i) => {
  if (!able) {
    if (i === 2) able = true;
    console.log(el, i);
  }
});





© 2023. by MyeongheeJung

Powered by MH.J