전개 구문 (Spread syntax)

지은·2022년 9월 12일
1

JavaScript

목록 보기
15/42

전개 구문(Spread syntax)

: spread 문법(...)은 객체나 배열을 개별 요소로 펼쳐준다.

1. 객체나 배열을 펼쳐서 다른 객체나 배열에 담을 수 있다.

{...obj} : 객체를 객체에 담을 때

const obj1 = {
	username: 'wlwl99',
  	age: 26,
}

const obj2 = {...obj1}; // 새로운 객체를 만들어 ...obj를 할당한다.

console.log(obj1);  // {username: 'wlwl99', age: 26}
console.log(obj2); // {username: 'wlwl99', age: 26}

console.log(obj1 === obj2) // false

➡️ 이렇게 전개 구문을 이용해 객체를 복사하면, 두 객체는 서로 다른 주소 값을 가진 독립적인 객체이다.

얕은 복사(shallow copy)

spread 문법을 이용한 복사는 원본을 shallow copy하여 새로운 복사본을 생성한 것이다.

  • spread 문법과 Object.assign()은 원본을 shallow copy한다.

[...arr] : 배열을 배열에 담을 때

const arr1 = ['banana', 'apple', 'grape'];

const arr2 = [...arr1]; // 새로운 배열을 만들어 ...arr을 할당한다.

console.log(arr1);  // ['banana', 'apple', 'grape']
console.log(arr2); // ['banana', 'apple', 'grape']

console.log(arr1 === arr2); // false

➡️ 위와 마찬가지로, 두 배열은 서로 다른 독립적인 배열이다.


{...arr} : 배열을 객체에 담을 때

: 배열을 객체에 담으면, 배열의 index가 key가 되고, 각 요소는 value가 된다.

let arr = ['a', 'b', 'c'];
let obj = {...arr};

console.log(obj); // {0: 'a', 1: 'b', 2: 'c'}

2. 배열을 풀어서 함수에 전달인자로 전달할 수 있다.

function sum(x, y, z) {
	return x + y + z;
}

const arr = [1, 2, 3];

sum(...arr); // 6
// ...[1, 2, 3]은 배열 안의 요소들을 개별 요소 1, 2, 3으로 분리한다.

rest parameter와 spread syntax 혼동하지 않기

rest parameter : spread 문법을 사용하여 정의한 매개변수

  • ...rest분리된 요소들을 함수 내부에 배열로 전달한다.
function func(arg1, ...rest) {
  console.log(arg1);  // 1
  console.log(rest);  // [2, 3]
}

func(1, 2, 3);

spread 문법을 사용한 전달인자

: 전달인자인 배열...분리하여 분리된 배열의 요소들을 순차적으로 매개변수에 할당한다.

function func(x, y, z) {
  console.log(x); // 1
  console.log(y); // 2
  console.log(z); // 3
}
>
func(...[1, 2, 3]);
// ...[1, 2, 3]는 [1, 2, 3]을 개별 요소로 분리한다.(-> 1, 2, 3)
// spread 문법에 의해 분리된 배열의 요소는 개별적인 전달인자로서 각각의 매개변수에 전달된다.
  • rest parameter는 반드시 마지막 매개변수여야 하지만, spread 문법을 사용한 전달인자는 위치를 자유롭게 할 수 있다.
function func(v, w, x, y, z) {
  console.log(v); // 1
  console.log(w); // 2
  console.log(x); // 3
  console.log(y); // 4
  console.log(z); // 5
}

func(1, ...[2, 3], 4, ...[5]);
// ...[2, 3]는 [2, 3]을 개별 요소로 분리한다.(-> 2, 3)
// ...[5]는 [5]를 개별 요소로 분리한다.(-> 5)

이 글은 아래 링크를 참고하여 작성한 글입니다.
https://poiemaweb.com/es6-extended-parameter-handling

profile
개발 공부 기록 블로그

0개의 댓글