포스코x코딩온 웹 풀스택 양성과정

[포스코x코딩온] 웹 풀스택 과정 12주차 회고 | React - map, filter, 단축평가

Codult 2024. 3. 29. 23:09
728x90

 

📌 map()

arr.map(callbackFunction, [thisArg])

  • callbackFunction
    : 새로운 배열의 요소를 생성하는 함수로, currentValue, index, array 3개의 인수를 가질 수 있다.
  • [thisArg]는 callbackFunction에서 사용할 this 객체로, 생략 가능하다.
let list = ['a', 'b', 'c', 'd', 'e'];
let items = list.map((txt, id, arr)=>{
  console.log("txt:", txt);
  console.log("id:", id);
  console.log("arr:", arr);
  return txt + id;
})
// txt: list(배열)를 순서대로 돌면서 나오는 값
// id: txt의 인덱스
// arr: 현재 반복을 돌고 있는 배열
// items: "txt+id"로 만들어진 배열


💡 React의 Component에 map() 적용하여 배열을 출력할 수 있다.

  • component에 map() 사용 시, "key" 사용 권장
    (React는 업데이트 전 기존 요소와 업데이트 요소를 비교할 때 key를 사용하기 때문)
  • 아래 예시에서 우선 index로 key설정 하였으나, index는 리스트의 순서가 변경되면 모든 key가 변경되므로, key는 index가 아닌 고유한 값으로 설정해야 한다.
function App() {
  const list = ["k", "d", "t", "w", "e", "b"];
  return (
    <>
      <ol>
        {list.map((value, idx)=> {
          return <li key={idx}>{value}</li>;
        })}
      </ol>
    </>
  )
}


📌 filter()

인자로 넘겨지는 콜백함수의 테스트(조건)를 통과하는 요소를 모아, 새로운 배열을 생성해준다.

let animals = ["dog", "cat", "rabbit"];
let newAnimals = animals.filter((animal)=>{
  return animal.length > 3
});
console.log(newAnimals); // ["rabbit"]


includes()를 활용하여, 검색도 가능하다.

let words = ["dog", "cat", "rabbit"];
let result = words.filter((word)=>{
  return word.includes("a");
});
console.log(result); //["cat", "rabbit"]


📌 단축평가

논리연산자를 사용하여, 조건에 따라 값을 결정 or 조건에 따라 특정 코드를 실행한다.

  • 논리연산의 결과를 결정하는 피연산자를 (타입 변환하지 않고 그대로) 반환한다는 것이 핵심이다!

💡 && 연산자를 사용한 단축 평가

A && B

  • A가 false면, B는 확인하지 않고 바로 A의 값을 반환
  • A가 true면, B의 값을 확인하여 반환

💡 || 연산자를 사용한 단축 평가

A || B

  • A가 false이면, B의 값을 확인하여 반환
  • A가 true이면, B는 확인하지 않고 바로 A의 값을 반환
단축평가 표현식 평가 결과
true && anything anything
false && anything false
true || anything true
false || anything anything
 
728x90