FE/JavaScript

Modern JS - 입문

잠수함 2022. 1. 3. 16:20
728x90

* 변수 사용

- 기존 JS qustnsms var, let, const 를 사용하였습니다.

- 모던 JS에서는 let, const를 사용하는것을 권장하며, var 사용은 지양하는것을 권장한다고 합니다.

 

* JS 객체 비구조화 할당

- 객체 비구조화 할당 문법을 사용하면 코드를 더욱 짧고 보기 좋게 작성 할 수 있습니다.

const ironMan = {
  name: '토니 스타크',
  actor: '로버트 다우니 주니어',
  alias: '아이언맨'
};

const captainAmerica = {
  name: '스티븐 로저스',
  actor: '크리스 에반스',
  alias: '캡틴 아메리카'
};

function print(hero) {
  const { alias, name, actor } = hero;
  const text = `${alias}(${name}) 역할을 맡은 배우는 ${actor} 입니다.`;
  console.log(text);
}

print(ironMan);
print(captainAmerica);

 

* forEach 내장함수

- 기존에 일반적으로 사용하는 for 문을 대체 시킬 수 있습니다.

const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];

superheroes.forEach(hero => {
  console.log(hero);
});

- 함수의 파라미터로 각 원소에 대해 처리하고 싶은 코드를 함수에 넣어줍니다.

 

* map 내장함수

- 배열 안의 각 원소를 변환 할 때 사용 되며, 이 과정에서 새로운 배열이 만들어집니다.

const array = [1, 2, 3, 4, 5, 6, 7, 8];

const square = n => n * n;
const squared = array.map(square);
console.log(squared);

- map 함수의 파라미터로는 변화를 주는 함수를 전달해줍니다.

 

* indexOf 내장함수

- 원하는 항목이 몇번째 원소인지 찾아주는 함수입니다.

const superheroes = ['아이언맨', '캡틴 아메리카', '토르', '닥터 스트레인지'];
const index = superheroes.indexOf('토르');
console.log(index);

- index 값이 0부터 시작해서 찾고자 하는 위치의 index를 알려줍니다.

 

* findIndex 내장함수

- 배열안에 있는 값이 숫자, 문자, 불리언이면 indexOf로 원소를 찾을 수 있지만, 배열 안에 있는 값이 객체이거나, 배열면 indexOf로 찾을 수 없습니다. 이럴 경우에 findIndex 함수에 검사하고자 하는 조건을 반환하는 함수를 넣어서 찾을 수 이습니다.

const todos = [
  {
    id: 1,
    text: '자바스크립트 입문',
    done: true
  },
  {
    id: 2,
    text: '함수 배우기',
    done: true
  },
  {
    id: 3,
    text: '객체와 배열 배우기',
    done: true
  },
  {
    id: 4,
    text: '배열 내장함수 배우기',
    done: false
  }
];

const index = todos.findIndex(todo => todo.id === 3);
console.log(index);

 

* find 내장함수

- findIndex와 비슷하지만, 찾아낸 값 자체를 반환시키는 함수 입니다.

const todos = [
  {
    id: 1,
    text: '자바스크립트 입문',
    done: true
  },
  {
    id: 2,
    text: '함수 배우기',
    done: true
  },
  {
    id: 3,
    text: '객체와 배열 배우기',
    done: true
  },
  {
    id: 4,
    text: '배열 내장함수 배우기',
    done: false
  }
];

const todo = todos.find(todo => todo.id === 3);
console.log(todo);

==> 결과: {id: 3, text: "객체와 배열 배우기", done: true}

 

* reduce 내장함수

- 주어진 배열에 대해 총합을 구해야 할 경우

const numbers = [1, 2, 3, 4, 5];
let sum = array.reduce((accumulator, current) => accumulator + current, 0);

console.log(sum);

- 첫번째 파라미터는 accumulator, current를 파라미터로 가져와서 결과를 반환하는 콜백함수

- 두번째 파라미터는 reduce 함수에서  사용 할 초깃값

 

* 객체 생성자

- 함수를 통해서 새로운 객체를 만들고 그 안에 넣고 싶은 함수, 값을 구현할 수 있게 해줍니다.

 function Animal(type, name, sound) {
  this.type = type;
  this.name = name;
  this.sound = sound;
  this.say = function() {
    console.log(this.sound);
  };
}

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say();
cat.say();

==> 결과: 멍멍, 야옹

- dog가 가지고 있는 say함수와 cat이 가지고 있는 say 함수가 코드가 똑같지만 객체가 생성 될 때 마다 함수도 새로 만들어져서 this.say로 설정 되고 있습니다.

- 같은 객체 생성자 함수를 사용하는 경우, 특정 함수나 값을 재사용 할 수 있는데 이것이 프로토타입입니다.

 

 * 프로토타입

- 객체 생성자 함수 아래에 .prototype.[원하는키] = 코드를 입력하여 사용가능합니다

function Animal(type, name, sound) {
  this.type = type;
  this.name = name;
  this.sound = sound;
}

Animal.prototype.say = function() {
  console.log(this.sound);
};
Animal.prototype.sharedValue = 1;

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say();
cat.say();

console.log(dog.sharedValue);
console.log(cat.sharedValue);

==> 
결과: 
멍멍
야옹
1
1

 

* 클래스

- ES6 에서부터 class 문법추가되었습니다.

- 객체 생성자로 구현했던 코드를 조금 더 명확하고, 깔끔하게 구현 할 수 있게 해줍니다.

- 클래스 내부의 함수를 '메서드'라고 부릅니다.

class Animal {
  constructor(type, name, sound) {
    this.type = type;
    this.name = name;
    this.sound = sound;
  }
  say() {
    console.log(this.sound);
  }
}

const dog = new Animal('개', '멍멍이', '멍멍');
const cat = new Animal('고양이', '야옹이', '야옹');

dog.say();
cat.say();

 

내용출처: https://learnjs.vlpt.us/basics/