Spread 구문

iadorora·2024년 11월 8일

daily record

목록 보기
19/27

✅ 예제1

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const arr3 = [...arr1, ...arr2];
console.log(arr3); //(6) [1, 2, 3, 4, 5, 6]

const arr4 = arr1.concat(arr2);
console.log(arr4); //(6) [1, 2, 3, 4, 5, 6]

✅ 예제2

const latte = {
  esspresso: '30ml',
  milk: '150ml'
};

const cafeMocha = {
  ...latte,
  chocolate: '20ml',
}

console.log(latte); // {esspresso: "30ml", milk: "150ml"}
console.log(cafeMocha); // {esspresso: "30ml", milk: "150ml", chocolate: "20ml"}
[...latte]; //error

(function (...args) {
  for (const arg of args) {
    console.log(arg);
  }
})(...cafeMocha); // Error

배열을 Spread 하면 새로운 배열 생성 or 함수의 아규먼트로 사용 가능하나,
객체로는 새로운 배열을 만들거나 함수의 아규먼트로 사용할 수는 없다!⭐

"객체를 spread할 때는 반드시 객체를 표현하는 중괄호 안에서 활용해야 한다."

const snacks = ['원카칩', '꿀버터칩', '헛스윙칩', '태양칩', '야채시간'];
const drinks = ['사이다', '콜라', '우유', '물', '커피', '레몬에이드'];

function printArguments(...args) {
  for (const arg of args) {
    console.log(arg);
  }
}

const mySnacks = [...snacks]
const myDrinks = [...drinks]

mySnacks.splice(2, 3);
myDrinks.splice(1);

const myChoice = [...mySnacks, ...myDrinks]

printArguments(myChoice); //[ '원카칩', '꿀버터칩', '사이다' ]
printArguments(...myChoice); //원카칩 꿀버터칩 사이다
profile
Archive

0개의 댓글