본문 바로가기

코드스테이츠

코드스테이츠 spread & ...args

 

Spread 문법 :배열을 풀어서 함수의 인자 값으로 넣은 후 계산하고 싶을 때  !!기존 배열을 없애지 않는다(immutable)

 

function sum(x,y,z){

return x+y+z;


}

const number = [1,2,3]

sum(...number) //배열을 각 각 요소로 불러오는 행위
6

 

 

 

어떤 값이 인자로 들어와도 이것을 배열로 바꾼 후 비교한다면 꼭 그 대상이 배열이 아니여도 가능한 것을 보여주는 문제 방법은 ...args

 

spread  && rest 예시

 

 function getAllParamsByArgumentsObj() {
      return arguments;
    }

getAllParamsByArgumentsObj("1","2","3")

 

 

==> argumnet {"0":"1",

                           "1":"2",

                           "2":"3"

 }

 

function getAllParamsByRestParameter(...args) {
      return args;
    }

 

==>getAllParamsByRestParameter("1","2","3")
       ['1', '2', '3']

 

 

 

rest 예시 ( 임이의 인자를 배열로 바꿔준다.)

 

 

  it('Rest Parameter는 인자의 일부에만 적용할 수도 있습니다.', function () {
    // rest parameter는 항상 배열입니다.
    function getAllParams(required1, required2, ...args) {
      return [required1, required2, args];
    }
    expect(getAllParams(123)).to.deep.equal( [123,undefined,[]]  );

    function makePizza(dough, name, ...toppings) {
      const order = `You ordered ${name} pizza with ${dough} dough and ${toppings.length} extra toppings!`;
      return order;
    }
    expect(makePizza('original')).to.equal('You ordered undefined pizza with original dough and 0 extra toppings!');
    
    expect(makePizza('thin', 'pepperoni')).to.equal('You ordered pepperoni pizza with thin dough and 0 extra toppings!');
    expect(makePizza('napoli', 'meat', 'extra cheese', 'onion', 'bacon')).to.equal('You ordered meat pizza with napoli dough and 3 extra toppings!');