...
점 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 ]
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.
// 요소가 한 개인 배열을 펼치더라도, 하나의 값으로 평가되지 않으므로 할당할 수 없다.
const numAry = [1];
const one = ...numAry; // SyntaxError: Unexpected token '...'
const member= ['일코딩', '이자바', '삼갑빠', '사오정'];
const newObj = {...member};
console.table(newObj);
/*
┌─────────┬──────────┐
│ (index) │ Values │
├─────────┼──────────┤
│ 0 │ '일코딩' │
│ 1 │ '이자바' │
│ 2 │ '삼갑빠' │
│ 3 │ '사오정' │
└─────────┴──────────┘
*/