🐶 etc/2022기록

[20230629]ES6 화살표(에로우) 함수,전개연산자(Spread Operator)

서카츄 2023. 6. 29. 13:04
   
        var add = function(){

        }//이름이 없는 함수

        var add = ()=>{

        }

 

    function add(x,y){
            return x + y;
        }//이름이 있는 함수

        var add = (x,y)=>{
            return x + y;
        }

 

let add2 = function(x,y){
            return x+y;
        }

        let add3 = (x,y)=>{
            return x + y;
        }
    let add3 = (x,y)=> x + y;  

중괄호 줄일 수 있음, 리턴 생략가능

에로우함수에서는 이름이 꼭 있는 함수로 만들어줘야한다.

 

 

매개변수가 하나일 때는 괄호 생략 가능

let add = x=> {
            return x*3;
        }

 

 

함수내에서 바로 리턴만 있을때 중괄호 생략 가능

즉시실행함수

function(){} --> ()=>{}
       
     
    (function(){
            console.log('즉시실행 함수가 작동함');
        })();

        (()=>{
            console.log('즉시실행 함수가 작동함');
        })();


 

매개변수 두개 예시

    function add(a,b){
            return a+b;
        }

        let add5 = (a,b)=>{
            return a+b;
        }

 

매개변수 한개 예시


        function multiply(x){
            return x*2;
        }
        document.write(multiply(5));


        let multiply = x => x*2;
        document.write(multiply(5));

리턴 하나밖에없으면 중괄호 생략가능, 리턴 생략가능

 

 

Spread Operator 전개 연산자

→ 전개 연산자는 주로 배열을 많이 사용

    //전개연산자는 주로 배열에 많이씀
        let arr1 = ['one','two'];
        let arr2 = ['three','four'];

        let combined1 = [arr1[0], arr1[1], arr2[0], arr2[1]];
        console.log(combined1);
    let combined2 = arr1.concat(arr2);
        console.log(combined2);
        let combined3 = [].concat(arr1,arr2);
        //배열을 만들고 뒤에 arr1+arr2를 추가한다
        console.log(combined3);

 

전개연산자를 사용하면 쉽게 묶을 수 있다 (스프레드 펼친다고 생각하면 쉽다)

let combined4 = [...arr1,...arr2];

 

+객체에도 써먹을 수 있음

        let objectOne = {
            one:1,
            two:2,
            other:0
        };

        let objectTwo = {
            three:3,
            four:4,
            other:-1
        };

        let result = {...objectOne,...objectTwo};
        console.log(result);

other은 두개가 있기때문에 결과값은 -1로 나옴