[JavaScript] 핵심 개념과 주요 문법 | spred, rest, 구조 분해 할당

Eunji Lee·2022년 11월 8일
0

[TIL] JavaScript

목록 보기
9/22
post-thumbnail

오늘 느낀 점

  • 클로저 개념이 왜 이렇게 어려운지,,, 알 것 같으면서도 잘 모르겠다,,,🤦🏻‍♀️ 
    → 지금 단계에서는 완벽하게 이해하지 못하는 개념들도 있는 것 같다. 처음부터 너무 깊게 알려고 하지 말고, 조금 더 많은 내용을 배운 다음에 다시 한 번 이해하도록 노력해보자
  • 부트캠프를 따라가고 있지만, 불안한 감정이 문뜩문뜩 떠오르곤 하는데 지금은 그냥 죽이 되든 밥이 되든 일단 가보는 게 중요하다는 생각이 든다. 일단 가보자~~!💃🏻



Chapter 4. ES6 주요 문법

  • ECMA Script(a.k.a ES) : Ecma International이 ECMA-262 기술 규격에 따라 정의하고 있는 표준화된 스크립트 프로그래밍 언어-> 쉽게 말하자면 표준화된 JavaScript
    • 현재 가장 최신 버전은 ES2019 (2019년 출시)
    • ES6(2015년 출시): 가독성과 유지보수성을 획기적으로 향상할 수 있는 문법이 많이 추가됨

4-1. spread 문법

특징

  • 주로 배열을 풀어서 인자로 전달하거나, 배열을 풀어서 각각의 요소로 넣을 때에 사용
  • 기존 배열을 변경하지 않음(immutable)
function sum(x, y, z) {
	return x + y + z;
}

const numbers = [1, 2, 3];

sum(...numbers); //6 출력

배열에 활용하기

배열 합치기

let parts = ['two', 'three'];
let numbers = ['one', ...parts, 'and', 'four'];

console.log(numbers); //['one', 'two', 'three', 'and', 'four'] 출력
let arr1 = [0, 1, 2];
let arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];
console.log(arr1); //[0, 1, 2, 3, 4, 5] 출력

배열 복사하기

let arr = [1, 2, 3];
let arr1 = [...arr]; // arr.slice() 와 유사
arr1.push(4);
console.log(arr1); // [1, 2, 3, 4]
console.log(arr); // arr 은 그대로 [1, 2, 3]을 유지

객체에 활용하기

객체 병합하기

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}

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

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]

4-2. 나머지 매개변수(rest)

파라미터를 배열의 형태로 받아서 사용할 수 있으며, 파라미터의 개수가 가변적일 때 유용함

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

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

4-3. 구조 분해 할당

  • spread 문법을 이용해서 값을 해체한 후, 개별 값을 변수에 새로 할당하는 과정
    → 배열이나 객체를 여러 변수로 "풀어" 사용할 수 있는 특수 구문
  • 변수 선언(var, let, const)과 함께 사용해야 함

배열 구조 분해

  • 항목을 변수에 복사하여 비구조화하기 때문에 배열 자체는 수정되지 않음
let arr = ['Thomas', 'Holland']
let [firstName, lastName] = arr;

console.log(firstName); //Thomas
console.log(lastName); //Holland
console.log(arr); //['Thomas', 'Holland']
  • 쉼표로 필요한 요소만 가져오기
let [firstName, ,lastName] = ["Thomas", "Stanley", "Holland", "Spider-man"];
console.log(lastName); //Holland
  • 누락된 값을 대체할 기본값 설정하기
let [name = "Guest", surname = "Anonymous"] = ["Amy"];
console.log(name); //Amy
console.log(surname); //Anonymous

객체 구조 분해

  • 속성의 순서는 상관 없음
let options = {
	title: "Menu",
	width: 100,
	height: 200
};

let {title, width, height} = options;
//아래 코드와 위의 코드는 동일한 결과임
//let {width, title, height} = options;

console.log(options);
  • 속성과 변수 간 매핑 지정하기
let options = {
	title: "Menu",
	width: 100,
	height: 200
};

let {title: t, width: w, height: h} = options;
console.log(t); //Menu
console.log(w); //100
console.log(h); //200
console.log(options); //{title: 'Menu', width: 100, height: 200}
  • 누락된 속성에 기본값 설정하기
let options = {
  title: "Menu"
};

let {width = 100, height = 200, title} = options;

console.log(title);  // Menu
console.log(width);  // 100
console.log(height); // 200

cf) 선언 없이 객체 리터럴(object literal) 비구조화 할당

var a, b;
({a, b} = {a: 1, b: 2});
console.log(a); // 1
console.log(b); //2

참고자료
javascript.info 구조분해할당

0개의 댓글