[JavaScript] spread/rest 문법 & 구조 분해 할당(destructing)

Hannahhh·2022년 7월 11일
0

JavaScript

목록 보기
16/47

🔍 spread/rest

2015년에 출시된 ES6에서는 가독성과 유지보수성을 향상할 수 있는 문법이 많이 추가 되었으며 (let, const,템플릿 리터럴 등) spread/rest 문법, 구조 분해 할당 또한 그 중 하나이다.

✔ spread

주로 배열을 풀어서 argument로 전달하거나 각각의 요소로 넣을 때 사용한다.

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

sum(...numbers) // 6

✔ rest

parameter를 배열의 형태로 받아서 사용할 수 있으며 parameter의 개수가 가변적일때 유용하다.

function sum(...theArgs) {
  return theArgs.reduce((previous, current) => {
    return previous + current;
  });
}

sum(1,2,3) // 6
sum(1,2,3,4) // 10

✔ 배열에서 사용

배열 합치기


//Example1
let parts = ['shoulders', 'knees'];
let lyrics = ['head', ...parts, 'and', 'toes'];

console.log(lyrics) // ['head', 'shoulders', 'knees', 'and', 'toes']

//Example2
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];  
// spread 문법은 기존 배열을 변경하지 않으므로(immutable)
// arr1의 값을 바꾸기 위해서는 재할당 해야한다.

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

//Example3
let arr = ['code', 'states']
let value = [
  ...arr,
  'pre',
  ...['course', 'student']
]

console.log(value)   // ['code', 'states', 'pre', 'course', 'student']
// 요소를 펼쳐서 넣어준다.

배열 복사

let arr = [1, 2, 3];
let arr2 = [...arr]; // arr.slice() 와 유사
arr2.push(4);  // 4
// spread 문법은 기존 배열을 변경하지 않으므로(immutable)
// arr2를 수정해도 arr은 바뀌지 않는다 .

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

✔ 객체에서 사용

let obj1 = { foo: 'bar', x: 42 };
let obj2 = { foo: 'baz', y: 13 };

let clonedObj = { ...obj1 };
let mergedObj = { ...obj1, ...obj2 };

console.log(clonedObj)  // {foo: 'bar', x: 42}
console.log(mergedObj)  // {foo: 'baz', x: 42, y: 13}  ,중복 키 foo 변경, 중복되지 않는 key값 x가 추가

✔ 함수에서 나머지 파라미터 받아오기

function myFun(a, b, ...manyMoreArgs) {
  console.log("a", a);
  console.log("b", b);
  console.log("manyMoreArgs", manyMoreArgs);
}

myFun("one", "two", "three", "four", "five", "six");

// a one
// b two
// manyMoreArgs ['three', 'four', 'five', 'six']



👀 구조 분해 할당(destructing)

spread 문법을 이용하여 값을 해체한 후, 개별 값을 변수에 새로 할당하는 과정이다.


✔ 분해 후 새 변수에 할당

배열

const [a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(a)     // 10
console.log(b)     // 20
console.log(rest)  // [30, 40, 50]

객체

객체에서 구조 분해 할당을 사용하는 경우, 선언과 함께 사용하지 않을 시 에러가 발생할 수 있다. ({}이 객체 리터럴이 아닌 블록으로 간주되기 때문)

const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}

console.log(a)     // 10
console.log(b)     // 20
console.log(rest)  // { c: 30, d: 40 }

예제: 함수에서 객체 분해

function whois({displayName: displayName, fullName: {firstName: name}}){
  console.log(displayName + " is " + name);
}

let user = {
  id: 42,
  displayName: "jdoe",
  fullName: {
      firstName: "John",
      lastName: "Doe"
  }
};

whois(user) // Jdoe is John




Reference: 코드스테이츠

0개의 댓글