Javascript with 드림코딩 2

커피 내리는 그냥 사람·2021년 4월 16일
0

기업협업 인턴십

목록 보기
7/16

1. Arrow Function은 무엇인가? 함수의 선언과 표현

1. 함수 기본

  1. 기본
  • function은 Object다.(변수, 파라미터, 리턴할수도 있다.)
function printHello(){
    console.log('hello')
}

printHello();

function log(message){
    console.log(message);
}

log('Hello')
log(12345)
function log(message : string) : number
함수     /             / 타입     /  리턴
  • 자바스크립트에서는 타입이 명확치 않아 쪼금 난해한 부분이 있음
  1. Object
function changeName(obj){
    obj.name = 'coder';
}

const ellie = {name : 'ellie'};
changeName(ellie);
console.log(ellie)
>>>{ name: 'coder' }

// object는 ref로 메모리에 저장되어 위의 함수에서 name이 메모리에 적용된 것
  1. default parameter : 따로 지정하지 않은 인자에 대해서 unknown 지정 가능, 일종의 디포트 값 저장

  1. Rest Parameter : ...(배열 형태로 전달)
function printAll(...args){
  for (let i = 0; i<args.length; i++){
    console.log(args[i]);
  }
}

printAll('dream','coding', 'ellie')

>>>
'dream'
'coding'
'ellie'
  • 파이썬처럼 하는 방법도 있음
for (const arg of args){
  console.log(arg)
}

2. scope : 지역 / 전역 변수

밖에서는 안이 보이지 않고 안에서만 밖을 볼 수 있다.

3. return : 모든 함수는 return

  • early return, early exit?
    -> 조건이 맞지 않으면 얼른 리턴, 조건이 맞을 때만 로직을 쭉 실행

4. callback-hell

function randomQuiz(answer, printYes, printNo){
  if (answer === 'love you'){
    printYes();
  } else {
    printNo();
  }
}

const printYes = function() {
  console.log('yes!')
};

const printNo = function() {
  console.log('No!')
}

randomQuiz('wrong', printYes, printNo);
randomQuiz('love you', printYes, printNo);

>>> No! / Yes!

여기서 리커젼 일어나면 콜백 헬 일어날 수 있음. 관련한 내용은 추후 콜백 관련한 강의 들으며 복습하기

5. arrow function

  • function() {} -> "() =>"

const add = function (a,b) {
return a+ b};

-> const add = (a, b) => a + b;

6. IIFE : 함수 선언 + 호출

(function hello() {
  console.log('IIFE')
})();

(괄호와 괄호)


2. 클래스와 오브젝트의 차이점(class vs object), 객체지향 언어 클래스 정리

1. class : 속성 + 메서드

  • by 객체지향 언어
  • ES6 이후에 추가된 내용
  • 문법만 클래스형태, 얹혀짐

1. 예제

class Person{
  constructor(name, age){
    // 생성자
    this.name = name;
    this.age = age;
  }
  	// 메서드
    speak(){
    console.log(`${this.name}: hello`)
  }
}

const ellie = new Person('ellie', 20)
console.log(ellie.name, ellie.age)
ellie.speak();

python class와 거의.. 진짜 똑같을 정도로 유사함.(instance 만드는 것 까지 유사)

2. getter / setter : 사용자가 값을 잘못 입력하는 것을 사전에 방지해주는 것

class User{
  constructor(firstName, lastName, age){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }
  
  get age(){
    return this.age;
  }
  set age(value){
    this.age = value;
}
}

const user1 = new User('Steve', 'Job', '-1');
console.log(user1.age);

이렇게 할 경우??

"RangeError: Maximum call stack size exceeded" : 무한 반복이 일어남

<최종 수정>

class User{
  constructor(firstName, lastName, age){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }
  
  get age(){
    return this._age;
  }
  set age(value){
    if (value < 0){
      throw Error('age can not be negative')
    }
    this._age = value;
}
}

const user1 = new User('Steve', 'Job', '-1');
console.log(user1.age);

3. public / private / static(클래스 본연 공통)

  • 너무 최신 기술이기 때문에 참고만 하기(추후 타입스크립트에서 참고할 것)

4. 상속 / 다양성

  1. 상속 예시
class Shape {
  constructor(width, height, color){
    this.width = width;
    this.height = height;
    this.color = color;
  }
draw(){
  console.log(`drawing ${this.color} color of`);
}

getArea() {
  return this.width * this.height;
}
}

// 상속 받는 클래스
class Rectangle extends Shape {}

const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw()
  1. overriding
class Rectangle extends Shape {}
class Triangle extends Shape {
  getArea() {
  return this.width * this.height / 2;
}}


const rectangle = new Rectangle(20, 20, 'blue');
rectangle.getArea()

const triangle = new Triangle(20, 20, 'red');
triangle.getArea() {
return (this.width * this.height) / 2}
  • 상속 받되 일부 기능 수정할 때
  • 부모의 메소드를 자식 메소드에서 사용할 땐 super.~(python과 동일)
  • 클래스에서 파생된 인스턴스인지 아는 방법
console.log(rectangle instanceof Rectangle);

3. Object 정리

1. object?

1. 기본개념

  • key, value의 집합체다.
  • 변수에는 값을 하나밖에 담을 수 없다. -> 여러 개를 담고 싶다.
  • 간편한 데이터 관리
  • 만드는 법 : {}, 클래스(new object)로 만들 수 있다.
  • 동적인 상태에서 변경(추가, 삭제)도 가능(런타임 시에도) -> 지양
    e.g ) 위에서 실컷 해놓고 다른데에서 요소를 넣기..

2. 접근법

  • ellie.name(코딩하는 순간) or ellie['name'](정확히 어떤 값이 올지 모르고 궁금할 때)

    약간 json 데이터 받을 때 뭐 받을지 몰라서 [] 쓰는 파이썬과 유사한 듯

2. shorthand(중복 될 때 안 귀찮게) & constructor Function

  • 함수를 만든다. 근데 리턴 값에서 키만 쓴다.
  • 더 간단하게? : 클래스 작성해버리기

3. in operator(key가 있니?)

  • console.log('name' in ellie)

4. for in / for of

for (key in ellie){
  console.log(key)
}
; key 출력

for (value of array){
  console.log(key)
}
; value 출력

5. 오브젝트 카피

const user4 = {}
Object.assign(user4, user);
console.log(user4);

4. array & API

  • 토끼와 당근 : 오브젝트
  • 이걸 담아 놓는다 : 자료구조

동적 타입... 한 바구니 안에 다양한 데이터가 담길 수는 있으나.. 지양

  • 자료구조와 알고리즘 : 검색, 삽입, 정렬, 삭제 효율성

1. 배열 만들기 및 활용

  • const arr1 = new Array or [1, 2]

  • 그 외 방식은 Python과 유사

  • foreach 등 조금 다른 방식

    배열 안에 들어있는 밸류들 마다 내가 전달한 함수들을 출력한다.

  • push, unshift, pop, shift... (저번 정리 확인)

  • shift, unshift : data 처리 속도 자체가 늦는다.(data 위치 때문에)

  • splice : 시작 인덱스~ 몇 개나 지울건지?, 지우고 새로운거 추가도 가능)

  • concat(배열) = 배열 합하기

  • indexOf('내용') : 몇 번째?(없으면 -1 ; 약간 파이썬 find 느낌)

  • include('내용') : 있는지?

파이썬 배열 공부할 때도 그랬지만 구글링하면서 필요할 때마다 찾아쓰면서 익숙해지는 것도 좋을 것 같다.


5. 10가지 배열 함수 & API

파이썬과 비슷한 점, 차이점 생각하며 보기

1. join(배열 해체)

const fruits = ['banana', 'apple', 'orange'];
const result = fruits.join()
console.log(result);
>>>'banana,apple,orange'
  • 이 때 join 안에 ',' 이런거 넣으면 파이썬처럼 배열 해쉬될 때 응용되어서 프린트 될 수 있음.

2. split : 조인이랑 반대

const fruits = 'banana,apple,orange';
const result = fruits.split(',');
console.log(result)

파이썬하고 약간 개념이 다름.

3. array.reverse()

  • 배열 반대로

4. array.slice()

  • 0~n-1까지만 잘린다.

4. array.find()

array.find(function (student)=>return student.score === 90;)
  // 순차적으로 호출될 때 90점인 학생 리턴
  • 해당하는 요소를 return 해주는 api

5. .map()

  • 배열 안의 있는 모든 요소를 콜백함수를 호출하면서 가공되어진 값으로 대체하는 것
const result = students.map((student)=> student.score)
// 원래 객체인데 점수만 있는 배열 만들기

6. some()

const result = students.some((student)=> student.score < 50)
// 한 사람이라도 50점 미만안거 있나?
  • every는 모든 값이 그래야 함

7. reduce(prev, curr)

  • 순차적 전달
    1 2
    2 3
    3 4...
    (어떤 값을 누적하는구나!)
    마지막에 모든 값이 합해짐
  • reduceRight : 반대로
  • 예시 : 학생 점수 평균 구하기
const result = students.reduce((prev, curr) => prev + curr.score, 0)
console.log(result / student.length -1)

average 등 더 쉬운 방법은 없을까?

profile
커피 내리고 향 맡는거 좋아해요. 이것 저것 공부합니다.

0개의 댓글