JavaScript

[ JavaScript ] Rest parameter, Spread Syntax, 구조 분해 할당

duqrlcks 2022. 4. 30. 10:36
반응형

MDN 웹문서를 참고해 사용법만 아주 간단하게 정리해봤다. 

 

Rest parameter

함수의 매개변수 이름 앞에 ...을 붙여서 정의한 매개변수를 의미한다. Rest 파라미터는 함수 인자들을 배열로 받는다

function foo(...rest) {
    console.log(Array.isArray(rest)); // Array
    console.log(rest); // [1,2,3,4]
}

foo(1,2,3,4);

 

rest 파라미터는 반드시 마지막에 위치해야 한다. 아래와 같이 사용할 수 있다. 

// rest 앞쪽은 다른 변수로 지정해서 받을 수 있다
function foo(first, second, ...rest) {
    console.log(first, second); // 1 2
    console.log(rest); // [3,4]
}

foo(1,2,3,4);


// rest는 빈 배열일 수 있다.
function boo(first, ...rest) {
    console.log(first); // 1
    console.log(rest); // []
}

boo(1);


// rest가 앞으로 오면 에러 난다.
function bar(...rest, last) {
    console.log(rest, last);
}

bar(1, 2, 3); // Error

 

Spread Syntax

이터러블 객체를 개별 요소로 분리한다. 이터러블 객체로는 Array, String, Map, Set, DOM 등이 있다. 객체는 해당 안됨! Rest와 마찬가지로 ...을 쓴다.

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

console.log(..."HI") // H I



// 함수 인수로 사용 가능
function foo(...rest) {
    console.log(rest); // [1,2,3]
}

foo(...[1,2,3]);

 

rest와 다르게 위치에 제한이 없다. 꼭 마지막에 위치할 필요는 없다.

const ary = [1, ...[2, 3], ...[4]] // [1,2,3,4]

ary.push(...[5,6]); // [1,2,3,4,5,6]

 

 

구조 분해 할당

배열 구조 분해

1. 기본 변수 할당

let foo = [1, 2, 3, 4]
let [one, two, three, four] = foo;

console.log(one);
console.log(two);
console.log(three);
console.log(four);


// 구조 분해 할당으로 변수 swap
let a = 'a', b = 'b';
[a, b] = [b, a] 
console.log(a, b); // b a

 

2. 함수 반환값 분해

function f() {
    return [1, 2, 3];
}

let a, b;
[a, b] = f();
console.log(a, b); // 1 2  ->  배열 크기에 맞게 할당


//일부 반환값 무시 가능
[a, , b] = f();
console.log(a, b); // 1 3

 

3. rest 파라미터 활용

let [a, ...b] = [1, 2, 3, 4];

console.log(a); // 1
console.log(b); // [2, 3, 4]

객체 구조 분해

1. 기본 할당

let o = {p: 42, q: true};
let {p, q} = o;

console.log(p); // 42
console.log(q); // true


// 변수 선언을 분리할때 주의!
let a, b;
{a, b} = {a: 1, b: 2}; // 불가능
({a, b} = {a: 1, b: 2}); // 가능

 

2. 새로운 변수 이름으로 할당

let user = {
    id: 3,
    firstName: 'Chan',
    lastName: 'Lee',
    body: {
        weight: 80,
        height: 200
    }
};

// 객체 프로퍼티: 할당 변수이름
let { firstName: fName, 
    lastName: lName,
    body: {weight : uWeight}} = user;

// fName = user.firstname
// lName = user.lastName
// uWeight = user.body.weight

console.log(fName, lName, uWeight); // Chan Lee 80

 

3. rest, spread 활용

// 객체 내부에서는 객체에 spread 적용 가능
const obj = { a: 1, b: 2 };

console.log(...obj) // Error
console.log({...obj}) // { a: 1, b: 2 }


// spread
const n = { x: 1, y: 2, ...{ c: 3, m: d } };
console.log(n); // { x: 1, y: 2, c: 3, d: 4 }


// rest + 구조분해 할당
const { x, y, ...z } = n;
console.log(x, y, z); // 1 2 { c: 3, d: 4 }


// 객체 병합
const merged = { ...{ x: 1, y: 2 }, ...{ y: 10, z: 3 } };
console.log(merged); // { x: 1, y: 10, z: 3 };


// 프로퍼티 변경 - 뒤에 위치한 값으로 변경
const changed = { ...{ x: 1, y: 2 }, y: 100 };
console.log(changed); // { x: 1, y: 100 }


// 프로퍼티 추가
const added = { ...{ x: 1, y: 2 }, z: 0 };
console.log(added); // { x: 1, y: 2, z: 0 }

 

 

 

<참조>

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters   

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax   

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment   

 

 

반응형