본문 바로가기

TIL

Spread & Rest Operator

 

  • spread operator

-used to split up array elements or object properties

const newArr = [...oldArr, 1, 2];
const newObj = {...oldObj, newProp: 5};

 

const numArr1 = [1, 2, 3];


const numArr2 = [...numArr1, 4, 5, 6];
console.log(numArr2);  //[1, 2, 3, 4, 5, 6];


const numArr3 = [numArr1, 4, 5, 6];
console.log(numArr3);   //[[1, 2, 3], 4, 5, 6];

 

 

const person = {
     name: 'Max'
};

const newPerson = {
     ...person,
     age: 28
}

console.log(newPerson);

[Object Object]{
     age: 28,
     name: "Max"
}

 

 

 

 

 

 

 

  • rest operator

-used to merge a list of function argumets into an array

(function arguments를 하나의 array로)

function sortArgs(...args){
     return args.sort()
}

 

const filter = (...args) => {
     return args.filter(el => el===1);
}


console.log(filter(1, 2, 3)); //[1]

'TIL' 카테고리의 다른 글

Primitive Type과 Reference Type  (0) 2020.08.04
Destructuring  (0) 2020.08.04
let과 const (feat. var) --정리 현재진행형  (0) 2020.08.03
String.prototype.split()  (0) 2020.07.20
array 비우기  (0) 2020.07.20