[JavaScript] Spread 구문

iberis2·2023년 1월 4일
0

Spread

... 점 3개를 넣어 배열의 요소들을 펼칠 수 있다.

const myNum = [1, 2, 3, 4, 5]

console.log(myNum); // [1, 2, 3, 4, 5]
console.log(...myNum); // 1 2 3 4 5

배열 복사

const originalAry = [1, 2, 3];

// slice를 사용해서 복사
const sliceCopy = originalAry.slice();
sliceCopy.push(4);

// spread를 사용해서 복사하면, 요소 추가도 바로 할 수 있다.
const spreadCopy = [0, ...originalAry, 4];


console.log(originalAry); // [ 1, 2, 3 ]
console.log(sliceCopy); // [ 1, 2, 3, 4 ]
console.log(spreadCopy); // [ 0, 1, 2, 3, 4 ]

객체 복사

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

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

console.log(cafeMocha); // { espresso: '30ml', milk: '150ml', chocolate: '20ml' }

배열 합치기

const num1 = [1, 2, 3];
const num2 = [4, 5, 6];

const num4 = num1.concat(num2);
// .concat 매서드보다 spread가 직관적이다. 
const num3 = [...num1, ...num2];

console.log(num3); // [ 1, 2, 3, 4, 5, 6 ]
console.log(num4); // [ 1, 2, 3, 4, 5, 6 ]

함수의 argument로 활용

const introduce = function (name, age, job) {
  console.log(`Hi my name is ${name}.
I'm ${age}years old.
I'm a ${job}.`);
};

const intAry = ["김코딩", 20, "student"];
introduce(...intAry);
// Hi my name is 김코딩.
// I'm 20years old.
// I'm a student.

💡rest Parameter와의 비교

rest 파라미터는 함수에서의 여러개의 argument들을 하나의 parameter로 묶는 방식이다.(배열로 전달됨)
spread는 하나로 묶여있는 값을 각각의 개별 값으로 펼치는 방식이다.

const otherIntroduce = function (...rest) {
  console.log(`Hi my name is ${rest[0]}.
I'm ${rest[1]}years old.
I'm a ${rest[2]}.`);
};

otherIntroduce("김코딩", 20, "student");
Hi my name is 김코딩.
I'm 20years old.
I'm a student.

💡spread 구문의 특이사항

  1. spread 구문은 하나로 묶인 값을 여러개로 펼친 개념이다.
    즉, 하나의 값이 아닌 여러 값의 목록으로 평가된다.
// 요소가 한 개인 배열을 펼치더라도, 하나의 값으로 평가되지 않으므로 할당할 수 없다.
const numAry = [1];

const one = ...numAry; // SyntaxError: Unexpected token '...'
  1. 배열을 ⇨객체로 만들 수 있다.
    인덱스 번호가 프로퍼티 네임이 된다.
    ❌ 단, 객체를 배열로 만들 수는 없다.
const member= ['일코딩', '이자바', '삼갑빠', '사오정'];
const newObj = {...member};

console.table(newObj);
/*
┌─────────┬──────────┐
│ (index) │  Values  │
├─────────┼──────────┤
│    0    │  '일코딩'  │
│    1    │  '이자바'  │
│    2    │  '삼갑빠'  │
│    3    │  '사오정'  │
└─────────┴──────────┘
*/
profile
React, Next.js, TypeScript 로 개발 중인 프론트엔드 개발자

0개의 댓글