[dream coding] 전개구문 Spread 문법 12강 TIL

sohyun·2022년 7월 6일
0

드림코딩 강의 정리

목록 보기
13/20
post-thumbnail

Spread 문법

  • (...Iterable)
  • Spread 연산자, 전개구문
  • 모든 Iterable은 Spread 될 수 있다
  • 순회가 가능한 모든 것들은 촤르르르륵 펼쳐 질 수 있다
  • Spread 문법을 사용하면 유사 배열 객체(Array-like Object)를 배열로 손쉽게 변환할 수 있다.
  • func(...iterable)
  • [...iterable]
  • { ...obj }

💡 함수의 인수로 사용하는 경우

  • 배열의 요소를 분해하여 순차적으로 파라미터에 할당
  • Rest 파라미터는 Spread 문법을 사용하여 파라미터를 정의한것을 의미, 혼동 주의!!!
  • Rest 파라미터는 반드시 마지막 파라미터
  • Spread문법을 사용한 인수는 자유롭게 사용가능
/* Spread 문법을 사용한 매개변수 정의 (= Rest 파라미터)
   ...rest는 분리된 요소들을 함수 내부에 배열로 전달한다. */
function foo(param, ...rest) {
  console.log(param); // 1
  console.log(rest);  // [ 2, 3 ]
}
foo(1, 2, 3);

/* Spread 문법을 사용한 인수
  배열 인수는 분리되어 순차적으로 매개변수에 할당 */
function bar(x, y, z) {
  console.log(x); // 1
  console.log(y); // 2
  console.log(z); // 3
}

// ...[1, 2, 3]는 [1, 2, 3]을 개별 요소로 분리한다(-> 1, 2, 3)
// spread 문법에 의해 분리된 배열의 요소는 개별적인 인자로서 각각의 매개변수에 전달된다.
bar(...[1, 2, 3]);


function foo(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
}

// ...[2, 3]는 [2, 3]을 개별 요소로 분리한다(→ 2, 3)
// spread 문법에 의해 분리된 배열의 요소는 개별적인 인자로서 각각의 매개변수에 전달된다.
foo(1, ...[2, 3], 4, ...[5]);

💡 배열에서 사용하는 경우

concat ( )

  • 기존의 배열 요소를 새로운 배열 요소의 일부로 만들기
let arr =[1,2,3];
console.log(arr.concat([4,5,6])); //[1,2,3,4,5,6]

/* Spread 문법을 사용하여 배열 리터럴만으로도 새로운 배열요소의 일부로 만들 수 있음*/
const newArr = [1,2,3];
console.log([...arr,4,5,6])	//[1,2,3,4,5,6]

push ( )

  • 기존 배열에 다른 배열의 개별 요소를 각각 push 한다
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

// ...arr2는 [4, 5, 6]을 개별 요소로 분리한다
arr1.push(...arr2); // == arr1.push(4, 5, 6);

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

splice ( )

  • 기존 배열에 다른 배열의 개별 요소를 추가한다.
const arr1 = [1, 2, 3, 6];
const arr2 = [4, 5];

// ...arr2는 [4, 5]을 개별 요소로 분리한다
arr1.splice(3, 0, ...arr2); // == arr1.splice(3, 0, 4, 5);

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

slice ( )

  • 기존 배열을 복사한다
  • 이때 원본 배열의 각 요소를 얕은 복사(shallow copy)하여 새로운 복사본을 생성한다. 이는 Array#slice 메소드도 마찬가지다.
var arr  = [1, 2, 3];
var copy = arr.slice();

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

// copy를 변경한다.
copy.push(4);

console.log(copy); // [ 1, 2, 3, 4 ]
// arr은 변경되지 않는다.
console.log(arr);  // [ 1, 2, 3 ]

/*Spread 문법 사용시*/
const arr = [1, 2, 3];
// ...arr은 [1, 2, 3]을 개별 요소로 분리한다
const copy = [...arr];

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

// copy를 변경한다.
copy.push(4);

console.log(copy); // [ 1, 2, 3, 4 ]
// arr은 변경되지 않는다.
console.log(arr);  // [ 1, 2, 3 ]

Rest파라미터,concat(),obj 사용 예제

// Rest parameters
//함수에서 인자로 받는 갯수가 정해져 있지 않을 경우 마지막 인자는 스프레드연산자를 사용
function sum(first, second, ...nums) {
  console.log(nums);  // [ 0, 1, 2, 4 ]
}
sum(1, 2, 0, 1, 2, 4);

// Array Concat : 2개의 배열을 합쳐줌
const fruits1 = ['🍏', '🥝'];
const fruits2 = ['🍓', '🍌'];
let arr = fruits1.concat(fruits2);
console.log(arr); //[ '🍏', '🥝', '🍓', '🍌' ]
arr = [...fruits1, '🍓', ...fruits2]; 
console.log(arr); // [ '🍏', '🥝', '🍓', '🍓', '🍌' ]

// Object
const ellie = { name: 'Ellie', age: 20, home: { address: 'home' } };
const updated = {
  ...ellie,// 새로운 오브젝트를 만들고 배열을 전개구문 해준다
  job: 's/w engineer',
};
console.log(ellie); //{ name: 'Ellie', age: 20, home: { address: 'home' } }
console.log(updated);
/* {
  name: 'Ellie',
  age: 20,
  home: { address: 'home' },
  job: 's/w engineer'
} */
profile
냠소현 개발일지

0개의 댓글