[JS] JS 반복문 총 정리

Date:

Updated:

Categories:

Tags: ,


오늘은 꼭 JS 반복문을 마스터하자

JS에 있는 여러 반복문을 효율적으로 사용할 수 있도록 이번 기회에 정리해보려고 한다.

종류

  1. for - 일반적인 for문
  2. for in - 객체 key 열거 전용
  3. for of - 이터러블 순회 전용
  4. forEach() - 배열 순회 전용
  5. while - 일반적인 while문
  6. do while - 일반적인 do…while문
  7. Object 객체 메서드 - 객체 순회 전용
  8. Array.prototype 메서드 - 배열 전용


1. for - 일반적인 for문

: for (초기화식; 조건식; 증감식) { 실행 코드 }

for (let i=0; i<5; i++) {
  console.log(i);
}


2. for in - 객체 key 열거 전용

: for (const key in 객체) { 실행 코드 }

const obj = {
  name: 'jisu',
  job: 'FE Developer'
};

for (const key in obj) {
  console.log(`${key}: ${obj[key]}`);
}


3. for of - 이터러블 순회 전용

: for (const value of 이터러블) { 실행 코드 }

(이터러블 종류에는 String, Array, Map, Set, Dom 컬렉션(HTMLCollection, NodeList) 등이 있다.)

const arr = [1, 2, 3];

for (const value of arr) {
  console.log(value);
}


4. forEach() - 배열 순회 전용

: 배열.forEach((value, index, array) => { 실행 코드 })

[1, 2, 3].forEach((value, index, array) => {
  console.log(`${index}: ${value}`);
})


5. while - 일반적인 while문

: while (조건식){ 실행 코드 }

let num = 0;

while (num < 3) {
  console.log(num++);
}


6. do while - 일반적인 do…while문

: do{ 실행 코드 } while(조건식);

do {
  console.log('무조건 실행');
} while(false);


7. Object 객체 메서드 - 객체 순회 전용

Object.keys(객체)

: 객체의 key를 배열로 반환

const obj = {
  name: 'jisu',
  job: 'FE Developer'
};

Object.keys(obj); // [ 'name', 'job' ]
Object.values(객체)

: 객체의 value를 배열로 반환

const obj = {
  name: 'jisu',
  job: 'FE Developer'
};

Object.values(obj); // [ 'jisu', 'FE Developer' ]
Object.entries(객체)

: 객체의 [key, value]를 배열로 반환

const obj = {
  name: 'jisu',
  job: 'FE Developer'
};

Object.entries(obj); // [ [ 'name', 'jisu' ], [ 'job', 'FE Developer' ] ]


8. Array.prototype 메서드 - 배열 전용

forEach()

: 배열.forEach((value, index, array) => { 실행 코드 })

[1, 2, 3].forEach((value, index, array) => {
  console.log(`${index}: ${value}`);
})
.map()

: 배열.map((value, index, array) => { 실행 코드 })

const result = [1, 2, 3].map((value, index, array) => {
  console.log(value); // 1, 2, 3
  return value*10; // 각 요소에 10을 곱한 값을 배열로 반환
});

console.log(result); // [ 10, 20, 30 ]
.filter()

: 배열.filter((value, index, array) => { 실행 코드(return 값이 true인 value만 담아 새로운 배열 반환) })

const result = [1, 2, 3].filter((value, index, array) => {
  console.log(value); // 1, 2, 3
  return value%2 !== 0; // value가 홀수인 값들만 배열로 반환
});

console.log(result); // [ 1, 3 ]
.reduce()

: 배열.reduce((이전 값, 현재 값, 현재 index, array) => { 실행 코드 }, 초기값)

const result = [1, 2, 3].reduce((preValue, curValue, idx, arr) => {
  return preValue + curValue; // 누적 합
}, 100);

console.log(result); // 106