[자바스크립트 ES6] 02

ssook·2021년 8월 6일
0
post-thumbnail

✅ 객체와 배열

ES6부터 객체와 배열을 다루는 방법과 객체와 배열 안에서 변수의 영역을 제한하는
방법을 다양하게 제공하기 시작.
구조 분해, 객체 리터럴 개선, 스레드 연산자가 이에 해당한다.

📍 2.4.1 구조 분해를 사용한 대입

  • 구조 분해를 사용하면 객체 안에 있는 필드 갑을 원하는 변수에 대입
const sandwich = {
    bread: "bread",
    meat: "beef",
    cheese: "cheese",
    toppings: ["tomato", "onion"]
};

const {bread, meat} = sandwich;
console.log(bread,meat);
  • 아래처럼 객체를 분해해서 같은 이름의 변수에 넣어줌
  • 두 변수의 값은 같은 이름의 필드 값으로 초기화되지만, 두 변수를 변경해도 원래의 필드 값은 바뀌지는 않음.
const lordify = regularPerson => {
    console.log(`${regularPerson.firstname}`);
};

var regularPerson={
    firstname: "ssook",
    lastname: "choi"
};
lordify(regularPerson);
  • 객체의 필드에 접근하기 위해 점(.)과 필드 이름을 사용하는 대신,
    필요한 값을 구조 분해로 가져올 수 있음
const lordify2 = ({firstname}) => {
    console.log(`${firstname}`);
};

var regularPerson2={
    firstname: "ssook",
    lastname: "choi"
};
lordify2(regularPerson2);
  • 객체 안에 객체를 넣은 경우
const regularperson={
    firstname: "ssook",
    lastname: "choi",
    person:{
        firstname: "hi",
        lastname: "hello"
    }
};

const lorDify = ({person: {firstname}})=> {
    console.log(`${firstname}`);
};
lorDify(regularperson);

📍 2.4.2 배열 구조 분해하기

  • 배열을 구조 분해해서 값을 뽑아낼 수 있음.
const [firstname]=["ssook","sook","luel"];
console.log(firstname);
  • 불필요한 값을 콤마(,)를 사용해 생략하는 리스트 매칭을 사용 가능.
    변수에 대입하지 않고 무시하고 싶은 원소의 위치에 콤마를 넣으면 리스트 매칭을 사용하는 것.
const [,,thirdname]=["ssook","sook","luel"];
console.log(thirdname);

📍 2.4.3 객체 리터럴 개선

  • 구조 분해의 반대로, 구조를 다시 만들어내는 과정 또는 내용을 한데 묶는 과정
  • 현재 영역에 있는 변수를 객체의 필드로 묶을 수 있음.
const name = "탈락";
const elevation = 9738;

const funhike = {name, elevation};
console.log(funhike);
  • 객체의 키에 접근하기 위해 this를 사용
const name2 = "탈락";
const elevation2 = 9738;
const print=function(){
    console.log(`${this.name2}의 높이는 ${this.elevation2}`)
};
const funhike2={name2,elevation2,print};
funhike2.print();
  • 기존의 방식
var skier = {
    name: name,
    sound: sound,
    powderYell: function (){
        var yell = this.sound.toUpperCase();
        console.log(`${yell} ${yell} ${yell}!!!`)
    },
    speed: function (mph){
        this.speed=mph;
        console.log('속력',mph)
    }
}
  • 새로운 방식
const skier2 = {
    name: name,
    sound: sound,
    powderYell: function (){
        var yell = this.sound.toUpperCase();
        console.log(`${yell} ${yell} ${yell}!!!`)
    },
    speed(mph){
        this.speed=mph;
        console.log('속력',mph)
    }
}

📍 2.4.4 스프레드 연산자

  • 스프레드 연산자는 3개의 점(...)으로 이뤄진 연산자로
    여러 기능을 제공한다.

1.배열의 조합

  • 두 배열이 있다면 두 배열의 모든 원소가 들어간 세 번째 배열을 만들 수 있음.
const peaks = ["대청봉", "중청봉", "소청봉"];
const canyons = ["천불동계곡","가야동계곡"];
const seoraksan = [...peaks,...canyons];

console.log(seoraksan.join(','));
  • 원본 배열을 복사하는 기능을 수행할 수 있다.
const peaks = ["대청봉", "중청봉", "소청봉"];
const canyons = ["천불동계곡","가야동계곡"];
const seoraksan = [...peaks,...canyons];

//const [last]=peaks.reverse(); 이렇게 하면 원래 배열도 뒤집어진다.
const [last]=[...peaks].reverse(); // 안 뒤집어진 채로 잘 나온다.

console.log(last);
console.log(peaks.join(', '));
  • 스프레드 연산자를 사용해 배열의 나머지 원소들을 얻을 수 있다.
function  directions(...args) {
  let [start, ...remaining] = args;
  let [finish, ...stops] = remaining.reverse();

  console.log(`${args.length}`);
  console.log(`${start} 출발`);
  console.log(`${finish} 목적지`);
  console.log(`${stops.length}를 들립니다`);
}

directions(
        "서울",
        "수원",
        "천안", "대전","대구","부산"
);
  • 스프레드 연산자를 객체에도 사용할 수 있음.
  • 객체에 스프레드 연산자를 사용하는 방법도 배열에 스프레드 연산자를 사용하는 경우와 비슷
const morning ={
    breakfast: "냠냠",
    lunch: "냠냠냠"
};

const dinner = "냠냠?";
const meals = {
    ...morning,
    dinner
};

console.log(meals);
profile
개발자에서, IT Business 담당자로. BrSE 업무를 수행하고 있습니다.

0개의 댓글