TIL

Spread & Rest Operator

윰윰로그 2020. 8. 4. 22:51

 

  • 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]