[2024.08.02 TIL] JS 객체와 배열 구조 분해 할당

박지영·2024년 8월 12일
0

Today I Learned

목록 보기
7/67

JavaScript 객체와 배열 구조 분해 할당

  • 구조 분해 할당

    //객체 구조 분해 할당
    const user = {name : 손석구, age : 10};
    const {name, age} = user;
    
    console.log(name); // 손석구
    console.log(age); // 10
    //배열 구조 분해 할당
    const games = {'배그', '롤'}'
    const {pubg, lol} = games;
    
    console.log(pubg); // 배그
    console.log(lol); // 롤

    배열을 구조 분해 할당하면 순서는 index 순서과 같음

    //함수 내 구조 분해 할당
    
    //user 객체
    const getName = (user) => {
    	return user.name;
    }
    const getName = ({name, age}) => {
    	return name;
    }
    
    //user 배열
    const getName = (user) => {
    	return user[0];
    }
    const getName = ([name, age]) => {
    	return name;
    }

spread operator (전개 구문)

  • 전개 구문
    기존에 있는 객체나 배열의 내용을 그대로 가져오거나 새로운 값을 덧붙여서 새로운 객체나 배열을 생성하는 것. (기존의 데이터에는 영향을 주지 않는다.)
    const box = {size : 'big', color : 'red'};
    const newBox = {...box}; // {size : 'big', color : 'red'}
    const newBlueBox = {...box, color : 'blue' }; // {size : 'big', color : 'blue'}

자주 쓰이는 메소드

  • map()
    배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환.
    const array1 = [1,4,9,16];
    
    const map1 = array1.map(x => x * 2);
    
    console.log(map1); // [2, 8, 18, 32]
  • filter()
    주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환.
    const fruits = ['사과', '귤', '배', '감', '바나나', '키위']'
    
    const result = fruits.filter(fruit => fruti.length > 2); // 문자열 길이가 2를 초과한 요소
    
    console.log(result); // 바나나
profile
신입 개발자

0개의 댓글