🏫 Open API_JAVA

[16일차] new 연산자 / prototype / JSON / Math.@

Dorothy_YANG 2022. 8. 10. 18:29
728x90

20220810(수)

  • 목차
    - new 연산자
    - prototype
    - JSON
    - Math.@

< new 연산자 >

  • Heap에 Object를 할당하고 object의 ref 값을 리턴하는 연산자.

  • const a = new Date();
    생성자 : Object를 초기화하는 function
    1) 기본 생성자 (default Construction)
       - parameter X, JS 에선 기본 제공, 자동 호출
    2) 비기본 생성자 (Overloaded Construction)
       - parameter O, 기본 제공이 아닐 수도 있다.

  • const a = new Date();
    const today = new Date(); 에서 괄호가 필요한 이유?
    ➡ 괄호 안에는 초기화할 값을 넣는 것이다!

  • 생성된 객체는 기본생성자(객체를 초기화하는 메소드)로 초기화된다.
    *기본 생성자 : 개발자가 별도로 파라미터를 주지 않음 
                           개발자가 별도로 줬을 때는 기본 생성자가 실행되지 않음 (즉 다른 별도의 생성자가 실행됨)
    (function(){
        // new 연산자 : 새로운 연산자를 만들 수 있다! 값을 받아서 결과만 뱉으면 됨(마치 함수같은 것)
        // heap에 올라간 ref값을 리턴 new 객체형 (Data-Type)
        const today = new Date(); // 괄호가 필요한 이유? :

        console.log(today.getMonth()); // 7 : 0부터 1월
        console.log(today.getDay()); // 3 : 0부터 일요일

    })();

 

let a = 10; vs let a; let a = 10;.
let a = 10; let a; 
let a = 10;.
a를 만들면서 10으로 초기화한다. a를 만든다.
a에 10을 대입한다.
undefined vs null
undefined null
초기화되지 않았음(아무것도 없음)
= heap에 데이터만 올려놨을 때

변수를 선언하고 값을 할당하지 않은 상태
변수에 저장된 값이 null인 경우

 


< prototype > - DNA 같은 것! (대물림)

  • 의미
    객체를 이루고 있는 객체 특정 data-type에 공통적, 설계상 data이다.
    모든 object에는 다 prototype이 붙어있다.
    * 같은 prototype이어도 배열이 필요한 prototype이 있고 function이 필요한 prototype이 있다.

  • DNA ?
    ➡ prototype에 추가하면 묶여있는 모든 애들이 영향을 받음!
   (function(){

    let a = [11, 11, 33, 44, 55];
   
    // Array.prototype.indexOf() : arrray 객체가 공통적으로 갖고있는 indexof
    console.log(a.indexOf(11)); // 0 : 첫번째 요소인 11을 찾고 그만둔다.
    console.log(a.indexOf(44)); // 3 : 네번째 요소인 44를 찾고 그만둔다.
    console.log(a.indexOf(574)); // -1 : 존재하지 않으면 -1을 반환한다.
   

   })();

 

[연습문제]

더보기

a 배열에서 값이 있으면 true, 없으면 false 값을 출력하시오.

 

   (function(){

    let a = [11, 11, 33, 44, 55];  

    Array.prototype.hasData = function(value)
    {
        if(-1 === this.indexOf(value))
        {
            return false;
        }

        return true;
    }

    console.log(a.hasData(33));
   
    let b = [];
    console.log(b.hasData(42));
         
    })();

< JSON : JavaScript Object Notatioin >

  • xml이 너무 과도해서 토할 것 같아.. 간단하게 만듦(key : value)
    프로그래머들이 만든 것  (JSON 형태로 데이터를 주고받겠단 얘기)
(function(){
        const student = [
            {
                name : '도로시',
                age : 21,
                married : false
            },
            {
                name : '이순신',
                age : 43,
                married : true
            },
   
        ];

        //
        console.log(JSON.stringify(student));
        console.log(JSON.stringify(student, null, 2));

        // 다시 객체화 시키기
        const jsonInfo = JSON.stringify(student);
        console.log(JSON.parse(jsonInfo))

        const jsonObj = JSON.parse(jsonInfo);
        console.log(jsonObj[0].name);
        console.log(jsonObj[0].age);

    })();


< parse >

  • 문자열을 분해(token)해서 요한 정보로 재가공하는 처리

Dorothy 작업

 


< Math.@ >

  • Math.@
    Math.pow : 세제곱 반환 / Math.sqrt : 제곱근 반환 / Math.random : 랜덤 값 돌리기(소수점 값)
    Math.floor : 뒤를 잘라버린다 / Math.round : 올림

  • sort 기능
    : 외부 라이브러리(Lodash)

  • Font 기능 (web-font를 이용)
    1) 서버의 신뢰성
    2) 라이센스
    3) 과도한 web font 금지 

 

[연습문제]

// 로또번호 생성하는 함수 만들기 [Dorothy]
// 1~45 사이의 랜덤값 6개

    (function(){
    let lotto = [];
   
    let i = 0;
    let j = 0;

    for(let i = 0; i < 6; i++){
        let num = Math.floor(Math.random() * 44) + 1;

        for(let j in lotto){
            if(num == lotto[j]){
                num = Math.floor(Math.random() * 44) + 1;
            }
        }
       
        lotto.push(num);
    }

    document.write(lotto);

   
    })();

* for문쓰면 안돼! 6바퀴 도는 게 아냐. 

 

// 로또번호 생성하는 함수 만들기 [선생님 풀이]
// 1~45 사이의 랜덤값 6개
       
        (function(){
        const getLottoNumber = function()
        {
            const ranNumber = [];

            // ranNumber.length가 6이 될 때까지 계속
            let num = 0;
            while(ranNumber.length < 6)
            {
                // ranNumber의 개수가 6개가 될 때까지 계속
                // 1 ~ 45까지의 랜덤번호를 하나 만들어 낸다.
                num = Math.floor(Math.random() * 45) + 1;

                if (-1 === ranNumber.indexOf(num))
                {
                    ranNumber.push(num);
                }

                // 랜덤번호가 ranNumber배열에
                // 존재하지 하지 않는다면 ranNumber에 넣는다.
                // 만약 랜덤번호가 존재한다면 랜덤번호를 다시 만든다.  
            }
            return ranNumber;
        }
        for (let i = 0; i < 5; i++)
        {
            ranLine = getLottoNumber();
           
            ranLine = _.sortBy(ranLine);

            str = ranLine.join();
            document.body.innerHTML += `<h1>${str}</h1>`
        }
       

    })();    

 

 

 

 

728x90