JS | for in / for of / forEach / Map 비교

mogooee·2021년 12월 11일
0

for in

객체의 값을 확인할 수 있다. object의 key값의 개수만큼 반복하여 value값을 뽑아낸다.

for (variable in object) { ... }

const object = { a: 1, b: 2, c: 3 };

for(const key in object){
   console.log(`${key}: ${key[property]}`);
}
// "a: 1"
// "b: 2"
// "c: 3"


for of

이터러블한 객체(순회 가능한 자료구조)를 순회한다.

for (variable of iterable) {
statement
}

const array = ['a', 'b', 'c'];

for (const element of array) {
  console.log(element);
}

// "a"
// "b"
// "c"


forEach

forEach는 배열의 메서드이다. 인자로 함수를 받아(콜백함수) 각 배열 요소의 인덱스와 값들을 콜백 함수에 적용한다. map 메서드와 달리 return값은 undefined이다.

arr.forEach(callback(currentvalue[, index[, array]])[, thisArg])

const array = ['a', 'b', 'c'];

array.forEach(element,index) => {
  console.log(element)
  console.log(index)
  console.log(array)
});

// "a"
// "b"
// "c"
// 0
// 1
// 2

Map

callback 함수를 각각의 요소에 대해 한번씩 순서대로 불러와 함수에 적용한다는 점은 forEach 메서드와 같다. 하지만 map 메서드는 함수의 return값으로 새로운 배열을 반환한다. 이러한 특징으로 객체 원본의 불변성을 지킬 수 있다.

arr.map(callback(currentValue[, index[, array]])[, thisArg])

const array1 = [1, 4, 9, 16];

const map1 = array1.map(x => x * 2);

console.log(map1); // [2, 8, 18, 32]
console.log(array1); // [1, 4, 9, 16]

continue와 break

고차함수(forEach, map, filter...)는 continue와 break로 중간 흐름을 제어할 수 없다. 배열의 모든 요소를 돌지 않게 하기 위해 중간에 제어가 필요하다면 다음과 같이 해결할 수 있다.

  1. for / for in / for of 문을 이용

  2. every, some, find, findIndex 메서드를 활용

    • 위 메서드들은 배열 요소를 판별 함수에 전달하고, 그 결과의 참/거짓 여부에 따라 반복의 종료 여부를 결정하여 조기 종료가 가능하다.



Reference
https://developer.mozilla.org/ko/

profile
개발의 숲

0개의 댓글

관련 채용 정보