문법

ASOpaper·2022년 11월 16일
0

Javascript

목록 보기
10/11

ES6 문법

목표

  • spread/rest 문법을 사용할 수 있다.
  • 구조 분해 할당을 사용할 수 있다.

spread/rest 문법

spread 문법

주로 배열을 풀어서 인자로 전달하거나, 배열을 풀어서 각각의 요소로 넣을 때에 사용

함수

function sum(x, y, z) {
  return x + y + z;
}
const numbers = [1, 2, 3];
sum(...numbers) // 6

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 (4) ['three', 'four', 'five', 'six']

배열
spread 문법은 기존 배열을 변경하지 않으므로(immutable), arr1의 값을 바꾸려면 새롭게 할당해야 한다.

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

let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2]; // [0, 1, 2, 3, 4, 5]

let arr = [1, 2, 3];
let arr2 = [...arr]; // [1, 2, 3]
arr2.push(4); // [1, 2, 3, 4]

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

객체

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

rest 문법

파라미터를 배열의 형태로 받아서 사용할 수 있습니다. 파라미터 개수가 가변적일 때 유용합니다.

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

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

참조

전개구문
REST 피라미터

구조 분해(destructing)

구조 분해 할당

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

배열

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

객체
객체에서 구조 분해 할당을 사용하는 경우, 선언(const, let, var)과 함께 사용하지 않으면 에러가 발생할 수 있다.

const {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}
a // 10
b // 20
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) // 

참조

구조분해할당

JavaScript Koans(선문답)

추가학습

세미콜론을 안넣었을 때 발생하는 문제
세미콜론을 넣어야 하는 이유
웹페이지 로딩과정 이해
컴퓨터 구조와 운영체제 이해1
컴퓨터 구조와 운영체제 이해2
컴퓨터 구조와 운영체제 이해3
변수의 유효범위와 끌어올림

profile
개인 공부 일지

0개의 댓글