JS 고급-(3) Rest Parameter, =>, ``, ...

김수민·2022년 11월 28일
0

JavaScript

목록 보기
15/27

Rest Parameter ()

    function add(...rest){
      let sum= 0;
      rest.forEach(num=> sum= sum+num)
      return sum;
    }
    
    let result1= add(1,2,3);
    console.log(result1); 
    //👉 0+1+2+3 =6
    let result2= add(1,2,3,4);
    console.log(result2);
    //👉 0+1+2+3+4 =10
    let result3= add(1,2,3,4,5);
    console.log(result3);
    //👉 0+1+2+3+4+5 =15

함수에 파라미터를 몇개 사용할 지 선언하고 호출하면 그 범위내에서만 계산할 수 있다.
위의 예제는 나머지 함수를 이용하여 그를 응용한 것이다.


화살표 함수 =>

	const hello = name => "hello"+name;
    console.log(hello("aa"));
    //👉helloaa

❗ 화살표 함수 내의 this는 언제나 상위 스코프의 this를 가리킨다.
❗ 화살표 함수에서 객체를 호출할 때에는 상위에 ()로 감싸져 있어야 객체의 호출로 알아들을 수 있다.


Template Literals ``

    let str1="green";
    console.log(("안녕하세요 "+str1+"씨"));
    //위를 아래와 같이 작성한 것을 Template Literals라고 한다.
    console.log((`안녕하세요 ${str1}`));

변수에 할당된 문자열을 하나의 문자열로 병합할 때 더하기(+)를 사용하지 않고 하나의 문자열로 만들 수 있도록 해준다.


spread operator ...arr

	let arr1=[1,2,3];
    let arr2=[7,8,9];
    let arr3=[...arr1,4,5,6,...arr2];
	//👉arr3=[1,2,3,4,5,6,7,8,9]

배열에 있는 값을 하나하나 분해하여 새로운 요소로 할당한다.


profile
sumin0gig

0개의 댓글