[ JavaScript ] - Spread oprator

이예빈·2022년 5월 3일
0

Spread Operator

... -> 이런 형태로 된 것을 Spread Operator라고 합니다.
spread operator는 JavaScript ES6에 새롭게 추가된 기능으로, array나 string같이 반복할 수 있는 것들을 function의 인자나 array의 요소로 확장시키거나 펼칠 수 있게 합니다.

Syntax

  • function 호출에 사용하기 위해선
myFunction(...iterableObj);
  • Array에 사용하기 위해
[...iterableobj, '4','five','6'];
  • object에 사용하기 위해
let objClone = { ...obj }; // pass all key:value pairs from an object

📌예

Copy Array Using Spread Operator

배열을 복사하여 새로운 배열을 만들고 싶을 때 spreade operator를 사용할 수 있습니다.

예를 들어,

const arr1 = ['one', 'two'];
const arr2 = [...arr1, 'three', 'four', 'five'];

console.log(arr2); 
//  Output:
//  ["one", "two", "three", "four", "five"]

Clone Array Using Spread Operator

자바스크립트에서 Object는 values자체가 아니라 reference가 할당됩니다.

let arr1 = [ 1, 2, 3];
let arr2 = arr1;

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

// append an item to the array
arr1.push(4);

console.log(arr1); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 3, 4]

위의 예시를 보면,arr1arr2 는 동일한 배열의 reference를 갖게되므로 하나의 배열을 변경시켜도 결과적으로는 두 arr1arr2에 변경사항이 똑같이 반영된것을 확인할 수 있습니다.

그런데 만약, 같은 reference를 참조하지 않으면서 배열을 복사하고 싶다면,
Spread Operator를 사용하면 됩니다.

그렇게 하면 하나의 array에서의 변경사항은 다른 array에 영향을 주지 않게됩니다.
( Spread Operator를 이용하여 복제하면 아예다른 reference를 갖게 되기 때문이다.)

let arr1 = [ 1, 2, 3];

// copy using spread syntax
let arr2 = [...arr1];

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

// append an item to the array
arr1.push(4);

console.log(arr1); // [1, 2, 3, 4]
console.log(arr2); // [1, 2, 3]

Spread Operator with Object

Spread Operator를 Object를 복제하는데에도 사용할 수 있습니다.
( 사실 Array도 Object의 일종이므로 어쩌면 당연한 말..)

const obj1 = { x : 1, y : 2 };
const obj2 = { z : 3 };

// add members obj1 and obj2  to obj3
const obj3 = {...obj1, ...obj2};

console.log(obj3); // {x: 1, y: 2, z: 3}

Rest Parameter

spread opreator가 function의 인자로 사용될 수도 있는데,
이는 rest parameter라고 부릅니다.

let func = function(...args) {
    console.log(args);
}

func(3); // [3]
func(4, 5, 6); // [4, 5, 6]

여기서,

  • func()에 하나의 인자가 넘어가면 rest parameter는 하나의 인자만 취하고,
  • 3개의 인자가 넘어가면 rest parameter는 3개의 모든 인자를 취합니다.

뿐만아니라 다음과 같이 다수의 인자를 function에 넘길수도 있습니다.

function sum(x, y ,z) {
    console.log(x + y + z);
}

const num1 = [1, 3, 4, 5];

sum(...num1); // 8

spread operator를 이용해서 여러개의 인자를 넘겼는데,
이 경우엔 sum()에선 3개의 인자만 필요하므로 넘겨진 나머지는 무시하게 됩니다.

Note :
rest parameter를 사용하면 array의 elements처럼 인자가 전달되는 것이다.

참고
https://www.programiz.com/javascript/spread-operator
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

0개의 댓글