티스토리 뷰

JavaScript

JS - Spread 문법

김관장 2022. 4. 8. 14:03

1. Spread 문법

  • Spread 문법(Spread Syntax, ...)는 대상을 개별 요소로 분리한다.
  • Spread 문법의 대상은 이터러블이어야 한다.

* 이터러블?
- 이터러블 프로토콜([for...of], [전개 연산자], [비구조화] ..등, 이터러블이나 이터레이터 프로토콜을 따르는 연산자들과 함께
동작하도록 하는 약속된 규약)
을 준수한 객체를 이터러블이라 한다. 배열, 문자열, Map, Set이 있다. 

console.log(...[1,2,3]) // 1,2,3
console.log(...'Hello') // H e l l o
console.log(...new Map([['a','1'],['b','2']])); // ['a','1'] ['b','2']
console.log(...new Set([1,2,3])); // 1 2 3
console.log(...{a:1, b:2}); // Error

=> 배열, 문자열, Map, Set은 이터러블로 스프레드 문법의 사용이 가능하다.

2. 사용

(2-1) 함수의 인수로 사용하는 경우 

function test1(a, b, c){
  console.log(a); // 1
  console.log(b); // 2
  console.log(c); // 3
}

test1(...[1,2,3]); // = test1(1,2,3)


function test2(a, b, c, d, e){
  console.log(a); // 1
  console.log(b); // 2
  console.log(c); // 3 
  console.log(d); // 4
  console.log(e); // 5
}

test2(1,...[2,3],4,...[5]) // = test2(1,2,3,4,5)

(2-2) 배열에서 사용하는 경우

1. concat
let test = [1,2,3];
console.log(test.concat([4,5,6])); // ES5문법 1,2,3,4,5,6
console.log([...test,4,5,6])); // ES6문법 1,2,3,4,5,6

2. push
let test = [1,2,3];
let test2 = [4,5,6];
test.push(...test2);
console.log(test); // [1,2,3,4,5,6]

3. splice
let test = [1,2,3,6];
let test2 = [4,5];
test.splice(3,0,...test2);
console.log(test); // [1,2,3,4,5,6]

4. copy
let test = [1,2,3];
let copy = [...test];

copy.push(4);

console.log(test); // [1,2,3]
console.log(copy); // [1,2,3,4]

(2-3) 객체 리터럴 내부에서 사용하는 경우

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

// 특정 프로퍼티 변경
const changed = Object.assign({}, { x: 1, y: 2 }, { y: 100 });
console.log(changed); // { x: 1, y: 100 }

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

 

*참고 https://poiemaweb.com/es6-iteration-for-of

 

Iteration & for...of | PoiemaWeb

ES6에서 도입된 이터레이션 프로토콜(iteration protocol)은 데이터 컬렉션을 순회하기 위한 프로토콜(미리 약속된 규칙)이다. 이 프로토콜을 준수한 객체는 for...of 문으로 순회할 수 있고 Spread 문법의

poiemaweb.com

 

'JavaScript' 카테고리의 다른 글

JS - this 란?  (0) 2022.04.21
JS - String() 과 toString()  (0) 2022.04.13
JS - 배열 함수 sort()  (0) 2022.04.07
JS - JSX?  (0) 2022.03.31
JS - Map() 과 Set()  (0) 2022.03.02
댓글