[필기정리]Day53 - class, array, Fields 등

Web/javascript

2020. 9. 7. 14:29

# class

① class (틀)
 - template : 템플릿 
 - declare once : 한 번만 선언
 - no data in : 정의만 한 것이기 때문에 데이터가 없음

② object (내용물)
 - instance of a class : 클래스의 인스턴스
 - created many times : 여러 번 선언 가능
 - data in : 데이터가 실제로 있는 것

③ Object-oriented programming
-  class: template // 템플릿에 속함
- object: instance of a class
 - JavaScript classes
   introduced in ES6  -  class는 ES6에서 새롭게 추가된 개념
   syntactical sugar over prototype-based inheritance

   ㄴ기존에 존재하던 프로토타입 기반으로 문법만 클래스가 추가된 것

 

1. Class declarations : 클래스 선언

class Person{
    // constructor
    constructor(name, age){ // 생성자
        // fields - 데이터 클래스(인스턴스 변수만 있는 클래스)
        this.name = name;
        this.age = age;
    }

    // methods
    speak() {
        console.log(`${this.name}: hello!`);
    }
}

const ellie = new Person('ellie', 20); // 오브젝트 생성
console.log(ellie.name);
console.log(ellie.age);
ellie.speak(); // 결과 : ellie: hello!

 

2. Getter and setters 

class User{
    constructor(firstName, lastName, age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    get age() {
        return this._age; // age 호출 시 해당 메소드 호출됨
    }

    set age(value){ // 값을 설정, value 필요, _를 사용해 무한반복 되지 않도록 변수명에 변화를 줌
        // if(value < 0){
        //     throw Error('age can not be negative');
        // }
        this._age = value < 0 ? 0 : value; // 위와 동일 내용
    }
}

const user1 = new User('Steve', 'Job', -1); // 실수로 -1이라고 입력한 경우
console.log(user1.age);

 

3. Fields (public, private) - Too soon! 최근에 추가된 내용으로 아직 많이 사용하고 있진 않음

 

JavaScript reference

This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference.

developer.mozilla.org

class Experiment{ // 멤버변수만 있는 클래스
    publicField = 2;
    #privateField = 0; 
    // 지원하지 않는 브라우저 있는 경우 있어 신중히 사용할 것
}

const experiment = new Experiment();
console.log(experiment.publicField);
console.log(experiment.privateField);       // undefined

 

4. Static properties and methods - Too soon! 개념을 알아만 두기!

  공통적으로 사용하는 내용이라면 스테틱을 사용하여 메모리를 효율적으로 사용할 수 있다.

class Article{
    static publisher = 'Dream Coding';
    constructor(articleNumber){
        this.articleNumber = articleNumber;
    }

    static printPublisher(){
        console.log(Article.publisher);
    }
}

const article1 = new Article(1);
const article2 = new Article(2);
console.log(article1.publisher); 
// 결과 : undefined 출력 (스테틱변수이기 때문) 
console.log(Article.publisher);         // Dream Coding
Article.printPublisher();

스테틱은 오브젝트가 아닌 클래스 자체에 붙어 있기 때문에 클래스명으로 호출해야 한다. 

자바스크립트에서는 참조변수로 접근 불가능하고, class명으로만 접근 가능하다.

 

5. Inheritance (상속) - a way for one class to extend another class.

class Shape{ // 공통적으로 쓰이는 속성값이 들어있는 클래스
    constructor(width, height, color){
        this.width = width;
        this.height = height;
        this.color = color;
    }

    draw(){
        console.log(`drawing ${this.color} color!`);
    }

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

class Rectangle extends Shape{} // extends로 위의 Shape 클래스를 상속
class Triangle extends Shape{
    draw(){
        super.draw(); // 부모의 메소드를 호출
        console.log('🔺'); // 문자열
    }
    getArea(){
        return (this.width * this.height) / 2; // 필요한 함수들만 오버라이딩 하여 사용 가능 (다양성)
    } // 자바와 마찬가지로 메소드 오버라이딩(하위 클래스가 재정의하는 것) 가능
    
    toString(){
        return `Triangle: color: ${this.color}`;
    }
}

const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw();
console.log(rectangle.getArea()); // 결과 : 400
const triangle = new Triangle(20, 20, 'red');
triangle.draw();
console.log(triangle.getArea());

 

6. Class checking: instanceOf : 왼쪽의 오브젝트가 오른쪽의 클래스로 만들어진 것인지 확인하는 것       

console.log(rectangle instanceof Rectangle); // 형변환이 가능하다면 true, 불가능하면 false
console.log(triangle instanceof Rectangle);
console.log(triangle instanceof Triangle); // 결과 : false
console.log(triangle instanceof Shape);
console.log(triangle instanceof Object); // command + Object click 정의된 곳으로 이동 , 가장 최상위 class
console.log(triangle.toString()); 
console.log(triangle); // 자바에서는 참조변수를 넘기면 toString()이 자동으로 실행되지만 객체 자체가 리턴된다.

 

#array

1. Declaration : 배열 선언

const arr1 = new Array(); // new 키워드 사용한 방법
const arr2 = [1, 2]; // [ ]를 사용한 방법

 

2. Index position

const fruits = ['사과', '바나나'];
console.log(fruits);
console.log(fruits.length);
console.log(fruits[0]); // 첫 인덱스에 접근할 때
console.log(fruits[1]);
console.log(fruits[fruits.length - 1]); // 마지막 인덱스에 접근할 때

 

3. Looping over an array

a. for 

for(let i = 0;i < fruits.length; i++){
    console.log(fruits[i]);
}

 


b. for of : 데이터를 순차적으로 할당하는 방법

for (let fruit of fruits) {
    console.log(fruit);
}

 

c. forEach : 배열 안의 각 인덱스마다 전달한 콜백함수를 value 호출

fruits.forEach(function (fruit, index, array) { // array - 배열 그 자체
    console.log(fruit, index, array) // 결과 : 사과, 0, ["사과","바나나"]
 });
// 위와 동일 내용
fruits.forEach( (fruit) => console.log(fruit) ); // 결과 : 사과 바나나

 

4. Addition, deletion, copy

- push : add an item to the end - 배열의 가장 뒤에 넣는 것

fruits.push('딸기', '복숭아');
console.log(fruits); // 결과 : ["사과","바나나", "딸기", "복숭아"]

 

- pop: remove an item from the end - 배열의 가장 뒤에서 하나를 빼는 느낌으로 지우는 것

fruits.pop();
fruits.pop();
console.log(fruits);

 

- unshift: add an item to the beginning - 배열의 가장 앞에 하나를 추가하는 것

fruits.unshift('딸기', '레몬');
console.log(fruits);

 

- shift: remove an item from the beginning - 배열의 가장 앞에서부터 하나를 지우는 것

fruits.shift();
fruits.shift();
console.log(fruits);

 

// Tip : note!! shift, unshift are slower than pop, push

   ㄴ pop, push의 경우 뒤에서 단순 삽입, 삭제만 하면 되지만

       shift, unshift은 기존의 데이터들이 당겨져 오면서 움직여야 하기 때문에 속도가 느리다!

      ∴ 되도록이면 pop, push를 사용하는 것이 좋다!

 

- splice: remove an item by index position - 원하는 인덱스 포지션을 지우는 것

           몇 개를 지울 것인지 갯수를 설정하지 않으면 시작 번호 이후의 모든 인덱스가 삭제된다.

fruits.push('딸기', '복숭아', '레몬');
console.log(fruits);
fruits.splice(1, 1); // splice(지우기 시작하는 인덱스 번호, 몇개를 지울 것인지의 갯수)
console.log(fruits);
fruits.splice(1, 1, '사과', '수박'); // 지우고 나서 원하는 데이터를 넣고 싶은 경우
console.log(fruits);

 

- combine two arrays : 두 가지 배열을 묶어서 사용하는 경우

const fruits2 = ['모과', '코코넛'];
const newFruits = fruits.concat(fruits2); // concat으로 새로운 배열을 추가하여 리턴하게 됨
console.log(newFruits);

 

5. Searching : find the index

- indexOf : 몇 번째에 위치하는지 알고 싶을 때 사용, 없으면 -1을 반환 

console.log(fruits);
console.log(fruits.indexOf('사과'));
console.log(fruits.indexOf('수박'));
console.log(fruits.indexOf('코코넛'));

 

- includes : 해당 내용이 있으면 true, 없으면 false 반환

console.log(fruits.includes('수박'));
console.log(fruits.includes('코코넛')); 

 

- lastIndexOf : 가장 마지막에 있는 동일 값을 출력하는 경우

fruits.push('사과');
console.log(fruits);
console.log(fruits.indexOf('사과')) // 먼저 오는 동일 값의 인덱스 출력
console.log(fruits.lastIndexOf('사과')); //  가장 마지막에 오는 동일 값의 인덱스 출력

 

Q.

// Q1. make a string out of an array
{
    const fruits = ['apple', 'banana', 'orange'];
  }
  
  // Q2. make an array out of a string
  {
    const fruits = '사과, 키위, 바나나, 체리';
  }
  
  // Q3. make this array look like this: [5, 4, 3, 2, 1]
  {
    const array = [1, 2, 3, 4, 5];
  }
  
  // Q4. make new array without the first two elements
  {
    const array = [1, 2, 3, 4, 5];
  }
  
  class Student {
    constructor(name, age, enrolled, score) {
      this.name = name;
      this.age = age;
      this.enrolled = enrolled;
      this.score = score;
    }
  }
  const students = [
    new Student('A', 29, true, 45),
    new Student('B', 28, false, 80),
    new Student('C', 30, true, 90),
    new Student('D', 40, false, 66),
    new Student('E', 18, true, 88),
  ];
  
  // Q5. find a student with the score 90
  {
  }
  
  // Q6. make an array of enrolled students
  {
  }
  
  // Q7. make an array containing only the students' scores
  // result should be: [45, 80, 90, 66, 88]
  {
  }
  
  // Q8. check if there is a student with the score lower than 50
  {
  }
  
  // Q9. compute students' average score
  {
  }
  
  // Q10. make a string containing all the scores
  // result should be: '45, 80, 90, 66, 88'
  {
  }
  
  // Bonus! do Q10 sorted in ascending order
  // result should be: '45, 66, 80, 88, 90'
  {
  }
  

 

 

Q1. make a string out of an array : 배열을 문자열로 바꿔라

A.

{
  const fruits = ['apple', 'banana', 'orange'];
  const result = fruits.join();
  // const result = fruits.join(', '); // 세 가지 방법으로 나눌 수 있음
  // const result = fruits.join('|');
  // const result = fruits.join(', and ');
  console.log(result);
}

 

Q2. make an array out of a string : 문자열을 배열로 바꿔라

A.

{
  const fruits = '사과, 키위, 바나나, 체리';
  const result = fruits.split(','); // 세 가지 방법
  // const result = fruits.split(',', 2); // 값을 2로 주면 2개짜리 배열이 만들어짐
  // const result = fruits.split(); // , 기준으로 만듬 
  console.log(result);
}

 

Q3. make this array look like this: [5, 4, 3, 2, 1] 

A.

{
  const array = [1, 2, 3, 4, 5];
  const result = array.reverse(); // 역순으로 만드는 것
  console.log(result);
  console.log(array); // reverse 사용 시 array 자체도 역순으로 바뀐다
}

 

Q4. make new array without the first two elements : 처음 2개를 제외하고 새 배열을 만들어라

A.

{
  const array = [1, 2, 3, 4, 5];
  const result = array.slice(2, 5); // 4 위치까지 출력되어야 하므로 5라고 한 것, 원래 array는 변경되지 않는다.
  // const result  = array.splice(0,2); // 1,2만 제외하는 것, 원래 array는 바뀐다
  console.log(result);
  console.log(array);
}

 

Q5. find a student with the score 90 : 점수가 90점인 학생을 찾아라

A. for문을 이용한 방법

class Student {
  constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  }
}
const students = [
  new Student('A', 29, true, 45),
  new Student('B', 28, false, 80),
  new Student('C', 30, true, 90),
  new Student('D', 40, false, 66),
  new Student('E', 18, true, 88),
];

{
  for(let i=0;i<students.length;i++){
    if(students[i].score === 90) console.log(students[i]);
  }
}

A. find 함수를 이용한 방법

class Student {
  constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  }
}
const students = [
  new Student('A', 29, true, 45),
  new Student('B', 28, false, 80),
  new Student('C', 30, true, 90),
  new Student('D', 40, false, 66),
  new Student('E', 18, true, 88),
];

 {
      // const result = students.find(function(student, index) // 콜백함수를 통해 students의 내용을 불러옴 
      // find 함수를 사용하여 점수 찾기 편함
        {
      //   console.log(student, index);
      // });
      // const result = students.find(function(student){
      //   return student.score === 90; // 조건에 해당하는 리턴값을 주게 되면 조건을 만족하는 것의 값을 리턴한다.
      // });
      const result = students.find((student) => student.score === 90); // 에로우 펑션으로 구현한 것
      console.log(result);
  }

 

Q6. make an array of enrolled students : 등록된 학생만으로 배열을 만들어라

A. for문을 이용한 방법

{
  let eStudents = [];
  for(let i=0;i<students.length;i++){
    if(students[i].enrolled === true) eStudents.push(students[i]); // eStudent에 해당 학생들만 넣는 것
  }
  console.log(eStudents);
}

A. filter함수를 이용한 방법

{
    const result = students.filter( (student) => student.enrolled ); // filter : 원하는 형태의 것만 걸러주는 역할
    console.log(result);
  }

 

Q7. make an array containing only the students' scores : 학생들의 점수로만 배열을 만들어라.

     // result should be: [45, 80, 90, 66, 88] 

A. for문을 이용한 방법

{
  let studentsScores = [];
  for(let i=0;i<students.length;i++){
    studentsScores.push(students[i].score); // studentsScores에 해당 점수들을 넣는 것
  } 
  console.log(studentsScores);
}

A. map함수를 이용한 방법

{
    const result = students.map( (student)=>student.score); // map : 원하는 형태로 가공할 때 사용
    console.log(result);
  }

 

Q8. check if there is a student with the score lower than 50 : 점수가 50점 미만인 학생이 있는지 체크하라.

A. for문을 이용한 방법

{
  for(let i=0;i<students.length;i++){
    if(students[i].score < 50) console.log("score가 50점 미만인 학생이 있음");
  }
}

A. some, every 함수를 이용한 방법

{
    const result = students.some( (student) => student.score < 50); // some : 조건에 맞는 것이 하나라도 있으면 true를 반환
    console.log(result);
    
    const result2 = students.every((student) => student.score < 50); // every : 전체 요소가 해당 조건에 해당하는 경우 true를 반환
    console.log(result2);

    const result3 = !students.every((student) => student.score >= 50); // some을 쓰면 편하지만 every를 사용하는 경우 예시임
    console.log(result3);
    console.log(!true);
  }

 

Q9. compute students' average score : 학생들의 점수 평균을 구하시오.

A. for문을 이용한 방법

{
  let sum = 0;
  for(let i=0;i<students.length;i++){
    sum += students[i].score;
  }
  console.log(sum/students.length);
}

A. reduce 함수를 이용한 방법

{
    // const result = students.reduce( (prev, curr) => { // reduce : prev(이전 값)과 curr(현재 값)을 매개변수로 받을 수 있다
    //   console.log('------------------');
    //   console.log(prev);
    //   console.log(curr);
    // });
    // const result = students.reduce( (prev, curr) => { // 콜백함수를 에로우 펑션을 만들어 넣어준 것
    //   console.log('------------------');
    //   console.log(prev);
    //   console.log(curr);
    //   return curr; // 현재 값을 리턴하여 다음에서 이전 값으로 쓸 수 있게 한다.
      
    // });
    // const result = students.reduce( (prev, curr) => {
    //   console.log('------------------');
    //   console.log(prev);
    //   console.log(curr);
    //   return curr;
    // }, 0); // 이전 값의 초기값이 0이 된 것
      
    // const result = students.reduce( (prev, curr) => {
    //   console.log('------------------');
    //   console.log(prev);
    //   console.log(curr);
    //   return prev + curr.score; // 이전 값 0 + 현재 점수
    // }, 0);
    // console.log(result);
      
    // const result = students.reduceRight( (prev, curr) => {
      // reduceRight는 오른쪽 끝에서부터!
    //   console.log('------------------');
    //   console.log(prev);
    //   console.log(curr);
    //   return prev + curr.score; 
    // }, 0);
    // console.log(result);
      
    const result = students.reduce( (prev, curr) => prev + curr.score, 0);
    console.log(result / students.length);

  }

 

 

Q10. make a string containing all the scores : 모든 점수를 문자열로 만드시오.

      // result should be: '45, 80, 90, 66, 88'

A. for문과 push함수를 이용한 방법

{
  let studentsScores = [];
  for(let i=0;i<students.length;i++){
    studentsScores.push(students[i].score); 
  }
  let result = studentsScores.join(); 
  console.log(result);
}

A. map, filter, join 함수를 이용한 방법

{
    // const result = students // 메소드 체이닝처럼 연결하여 사용한 것
    //   .map( (student) => student.score ) // 배열 리턴
    //   .filter( (score) => score >=50 ) // 배열 필터
    //   .join(); // 문자열 바꾸기
    // console.log(result);

    const result = students.map( (student) => student.score ).join();
    console.log(result);
  }

 

+ Bonus! do Q10 sorted in ascending order : 10번의 결과를 오름차순으로 정렬하시오.

// result should be: '45, 66, 80, 88, 90'

A.

{
  let studentsScores = [];
  for(let i=0;i<students.length;i++){
    studentsScores.push(students[i].score);
  }
  studentsScores.sort(function(a, b){return a - b});
  let result = studentsScores.join(); 
  console.log(result);
}

A.

{
    const result = students.map((student) => student.score) // score만의 배열 만듬
      .sort( ( a, b) => a - b) // 배열 정렬 
      .join(); // 문자열로 만듬
    console.log(result);
  }

 

[참고자료] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference

 

JavaScript reference

This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference.

developer.mozilla.org

 

728x90