Spread syntax (...)

하태현·2020년 11월 22일
0

javascript

목록 보기
14/23
post-thumbnail

구글링을 하다보면 자바스크립트 코드에 ... 기호를 볼수 있다.

스프레드 문법이라는 것인데 여러가지로 유용하게 쓰일 것 같아서 정리해본다.

Spread syntax (...)

기본적으로 스프레드 문법은 대상을 각 요소로 분리 시킨다.

console.log(...[1, 2, 3]) // 1, 2, 3
console.log(...'Hello');  // H e l l o

아래와 같은 용도로 많이 사용된다.

// # 배열 결합
const test1 = [1, 2, 3, 4];
const test2 = [5, 6, 7, 8];
console.log([...test1,...test2]); // [1, 2, 3, 4, 5, 6, 7, 8]

// # 배열 복사
const test3 = [...test1];
console.log(test1); // [1, 2, 3, 4]
console.log(test3); // [1, 2, 3, 4]
console.log(test1 === test3); // false

// # 	객체 결합
const test4 = { a: "test1", b: "test2" };
const test5 = { c: "test3", d: "test4" };
const test6 = { ...test4, ...test5 };
console.log(test6); // { a: "test1", b: "test2" , c: "test3", d: "test4" }

// # 객체 복사
const test7 = { ...test4 };
console.log(test7); // { a: "test1", b: "test2" };
console.log(test7 === test4); // false

// # Arguments 활용
function test8(data) {
  // 파라미터를 갯수에 맞게 작성해야한다.
  return data;
}
function test9(...data) {
  return data;
}
function test10(fixedData, ...data) {
  console.log(fixedData); // fixedData: 1
  return data;
}

console.log(test9(1, 2, 3, 4)) // data: [ 1, 2, 3, 4 ]
console.log(test10(1, 2, 3, 4)) // data: [ 2, 3, 4 ]
profile
왜?를 생각하며 개발하기, 다양한 프로젝트를 경험하는 것 또한 중요하지만 내가 사용하는 기술이 어떤 배경과 이유에서 만들어진 건지, 코드를 작성할 때에도 이게 최선의 방법인지를 끊임없이 질문하고 고민하자. 이 과정은 앞으로 개발자로 커리어를 쌓아 나갈 때 중요한 발판이 될 것이다.

0개의 댓글