[Javascript] Spread 연산자 (Spread Operator), 구조분해할당(Destructuring Assignment)

2023. 10. 29. 17:52프로그래밍/JavaScript

- Mozila Docs 참고

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

 

Spread syntax (...) - JavaScript | MDN

The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the propert

developer.mozilla.org

 

- Spread 연산자

Spread연산자는 반복가능한 객체들을 새로운 배열이나 객체로 바꿀 때 사용되는 연산자이다. 

문법은 ...을 사용한다. 

객체를 배열로 spread 할 수는 없다. 객체는 반복가능한 요소가 아니기 때문이다(not iterable).

예제를 보는 편이 훨씬 빠르다.

 

const array = [1, 2, 3, 4, 5, 6];
const newObj = {...array};
const stringArray = "hello my name is";
const stringObj = {...stringArray};
const obj = {a: 1, b: 2, c: 3, d: 4};
const obj2 = {e: 5, f: 6, g: 7};
const sumObj = {...obj,...obj2};
console.log(obj);
console.log(sumObj);
console.log(stringObj);

function test(a, b, c) {
    console.log(a, b, c);
}

const array2 = [1, 2, 3];
test.apply(null, array2);
console.log(...array2);
test(...array2);

const array3 = [4, 5, 6];
const sumArray = [...array2, ...array3];
console.log(sumArray);

var longArray = [1, 2, 3, 4, 5, 6, 7, 8];
var sum = 0; // 처음에 초기화를 해주지않으면 undefined 상태이다.
// 이후에 값을 할당시키면서 초기화하는 것은 괜찮으나 += 연산자를 사용했기 때문에 undefined와의 연산을 통해 NaN(Not a Number) 값을 가지게 된다.
for (const arg of longArray) {
    sum += arg;
}

//
console.log(sum);

spread는 쉽게 말해서 요소를 원소 하나하나로 분해하며 펼치는 것이다. 

배열은 인데스로 구분돼있기 때문에 값 하나하나가 모두 펼쳐지게 되고 객체의 경우에는 key와 value값을 그대로 가지고 펼쳐지므로 이 값은 배열에 저장할 수는 없게 된다. 즉 배열이나 문자열 같은 선형 자료구조는 새로운 배열로도 생성할 수 있고 새로운 객체로도 생성할 수 있지만 객체는 객체로만 다시 담을 수 있고 배열에는 저장하지 못한다.

 

 

- 구조분해 할당(Destructuring Assignment)

구조 분해 할당은 배열이나 객체를 변수에 바로 할당해줌으로써 편리하게 변수를 사용할 수 있게 만들어준다. 

배열의 경우 인덱스 차례대로 값이 할당되고 객체의 경우에는 해당 key값으로 접근하게 되면 value값을 갖는 변수를 가질 수 있다.

// 구조분해할당

const array = [1,2,3,4,5,6];
const [a,b,...c] = array;
console.log(a);
console.log(b);
console.log(c);
// 여기서 c를 rest(나머지)라고 부른다.

const obj = { a2: 1, b2: 2 };
const { a2, b2 } = obj;
console.log(a2);
console.log(b2);
// 위의 구조분해할당 문법은 아래와 같이 변수를 따로 선언한 것과 같다.
// is equivalent to:
// const a = obj.a;
// const b = obj.b;

// 배열과 객체의 구조분해할당의 차이점은 배열은 구조분해 할당을 할 때 인덱스 순서대로 할당시키고 객체의 경우에는
// key값을 통해 할당시킨다.

// binding exmplae
// 아래와 같이 값에 따라 따로 바인딩시킬 수도 있다.
const obj2 = { aa: 1, b: { c: 2 } };
const {
    aa,
    b: { c: d },
} = obj2;
// Two variables are bound: `a` and `d`
console.log(aa);
console.log(d)