자바스크립트를 허용해주세요.
[ 자바스크립트 활성화 방법 ]
from Mohon Aktifkan Javascript!
 

[Javascript] New Javascript 5장 - 스프레드 연산자

728x90

☑️ 1. 스프레드 연산자 (...)

스프레드 연산자는 배열이나 객체를 펼쳐 복사하거나, 함수인자로 전달할 때 사용되며 객체나 배열의 요소를 펼처서 복사 또는 병합할 때 사용되는 연산자입니다. 

  • 배열 예시
const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5, 6]; // arr1 요소를 펼처 arr2에 추가
console.log(arr2); // [1, 2, 3, 4, 5, 6]
const str1 = ["Hello"];
const str2 = [...str1, " ", "World"].join(""); // join을 사용해 arr1 arr2 문자 합치기
console.log(str2); // Hello World
  • 객체 예시
const nobj1 = { a: 1, b: 2 };
const nobj2 = { ...nobj1, c: 3 };
console.log(nobj2); // { a: 1, b: 2, c: 3}
// String obj
const sobj1 = { d: "Hello", e: "Java" };
const sobj2 = { ...sobj1, f: "Script" };

const combinedStr = [sobj2.d, sobj2.e].join(" ") + [sobj2.f].join("");
console.log(combinedStr); // Hello JavaScript
  • 함수 인자 전달
function sum(x, y, z) {
  return x + y + z;
}

const total = [1, 2, 3];
console.log(sum(...total)); // 6

function inter(_, m, j) {
  return m / j;
}

const fountain = [4, 20, 5];
console.log(inter(...fountain)); // 4 = 20 / 5

 

💡 배열/객체를 펼치거나, 여러 값을 함수 인자로 보낼 때 사용함


☑️ 2. 나머지 매개변수 (Rest Parameter)

나머지 매개변수는 함수의 여러 인자를 하나의 배열로 모을 때  사용되면 나머지 매개변수는 항상 함수 매개변수에 마지막에 위치해야 합니다.

// 나머지 매개변수는 항상 함수 매개변수의 마지막에 위치
function RestAll(...numbers) {
  return numbers.reduce((acc, cur) => acc + cur, 0); // ...numbers는 함수에 전달된 모든 인자를 배열로 모음
}

// 배열 메서드(ex.reduce, map)와 함께 사용가능
console.log(RestAll(1, 2, 3, 4)); // 10

☑️ 3. 스프레드와 나머지의 차이점

구분 스프레드 연산자 나머지 매개변수
위치 배열/객체 뒤에 사용 가능함 함수 매개변수 마지막에만 사용
용도 펼치기(spread) 모으기(rest)
반환 타입 펼쳐진 값 배열(array)

 

 

GitHub - javascript-only/newJSRoom: https://thinky.tistory.com/category/Front-End/JavaScript

https://thinky.tistory.com/category/Front-End/JavaScript - javascript-only/newJSRoom

github.com

 

728x90
LIST