[TIL #8-1 WECODE] forEach & Map 함수

Whoyoung90·2021년 3월 1일
0
post-thumbnail

210222 WECODE #8-1

Array.forEach()

  • forEach는 for문 대신 사용할 수 있는 반복문
  • 그러나 forEach는 아무것도 return하는 것이 없어서
  • forEach로 전달되는 callback 함수에서도 return하는 것이 없다. (map과의 차이점!)

빈 배열에 해당하는 element 채우기

<script>
let emptyArray = [];
let names = ['a', 'ab', 'cbb', 'ada'];

names.forEach((el) => {
  if (el.startsWith('a')) {
    emptyArray.push(el);
  }
});

console.log(emptyArray); //(3) ["a", "ab", "ada"]
</script>

forEach에서 현재 index를 알고 싶으면 두 번째 인자로 받으면 된다

<script>
 let findeIndex;
 let arr = ['a', 'b', 'c', 'd'];

  arr.forEach((el, idx) => {
    if (el === 'c') {
      findIndex = idx;
      return;
    }
  });
  console.log(findIndex); //2
</script>

forEach도 함수이므로, 중간에 반복문을 탈출하려면 return을 사용

<script>
let hasC = false;
let arr = ['a', 'b', 'c', 'd'];

arr.forEach(el => {
  if (el === 'c') {
    hasC = true;
    return;
  }
});
console.log(hasC); //true

arr.forEach(el => {
  if (el === 'e') {
    hasC = true;
    return;
  }
});
console.log(hasC); //false
</script>

Array.map()

  • map 메서드는 배열을 반복
  • callback 함수에서 return한 값으로 매(Each)요소들을 수정
  • map 메서드의 return 값은 "새로운 배열"로 "return"
<script>
let arr = [1, 2, 3];
let squares = arr.map(function (x) { 
  return x * x;
  })
console.log(squares); // [1, 4, 9]
</script>
profile
비전공으로 일식 쉐프가 되었듯, 배움에 겸손한 프론트엔드 개발자가 되겠습니다 :)

0개의 댓글

관련 채용 정보