1일1끄적

자바스크립트 입문, 객체2- 내장객체(1) 본문

개발/javascript

자바스크립트 입문, 객체2- 내장객체(1)

inkor 2021. 11. 22. 22:00

○ 내장객체

내장 객체(Built-in Object)란 브라우저의 자바스크립트 엔진에 내장된 객체를 말하며,

필요한경우 객체를 생성해서 사용할 수 있다. 

내장객체로는 문자(String), 날짜(Date),배열(Array),수학(Math), 정규 표현객체(RegExp Object)등이 있다.

 

○ 내장객체 생성하기

참조변수(인스턴스 이름)= new 생성 함수()

내장 객체를 생성하는 기본형. 객체를 생성할 떄는 new 키워드와 생성 함수를 사용한다.

 

 

new 키워드와 기본 객체 생성 함수 Object()를 이용하여 객체를 생성

<script>
    var hp = new Object();
    hp.color="blue";
    hp.price="1000000";
    hp.info= function(){
        document.write("핸드폰 색상:" + this.color,"<br>");
        document.write("핸드폰 가격:" + this.price,"<br>");
    }
    document.write("<h1>핸드폰 객체 메서드 호출</h1>");
    hp.info();
</script>

 

날짜 정보 객체

날짜나 시간 관련 정보를 제공받고 싶을 떄는 날짜 객체(Date Object)를 생성한다.

날짜 정보 객체는 날짜와 관련된 작업을 할 떄 유용한 객체다.

참조 변수 = new Date();
ex) var t = new Date();

참조 변수 = new Date("연/월일"); 
ex) var t = new Date("2021/11/18");
참조변수  new Date(연,월-1ㅡ일)
ex) var t = new Date(2021/10/18);

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Date

 

Date - JavaScript | MDN

JavaScript Date 객체는 시간의 한 점을 플랫폼에 종속되지 않는 형태로 나타냅니다. Date 객체는 1970년 1월 1일 UTC(협정 세계시) 자정과의 시간 차이를 밀리초로 나타내는 정수 값을 담습니다.

developer.mozilla.org

<script>
   var today = new Date();
   var currentMonth = today.getMonth();
   currentDate = today.getDate();
   currentDay=today.getDay();

   document.write("<h1>오늘 날짜 정보</h1>");
   document.write("현재 월: " + currentMonth, "<br>");
   document.write("현재 일: " + currentDate, "<br>");
   document.write("현재 요일: " + currentDay, "<br>");

</script>

 

 수학 객체

더하기, 곱하기, 나누기 등은 산술 연사자를 사용하면 되지만, 그 외의 산술 연산자로 구할 수 없는 것들을

수학 객체 메서드를 이용하면 최솟값, 반올림값 등 수학과 관련된 일련의 작업들을 처리할 수 있다.

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Math

 

<script>
    var num = 2.1234;

    var maxNum = Math.max(1, 5, 7, 10); // 최댓값
    var minNum = Math.min(1, 5, 7, 10); // 최소값
    roundNum = Math.round(num); // 소수점 첫째 자리 반올림
    floorNum = Math.floor(num); // 소수점 첫째 자리 내림
    ceilNum = Math.ceil(num); // 소수점 첫째 자리 올림
    rndNum = Math.random(); // 0 과 1 사이 랜덤값 발생
    piNum = Math.PI // 원주율 상수를 반환 

    document.write(maxNum, "<br>");
    document.write(minNum, "<br>");
    document.write(roundNum, "<br>");
    document.write(floorNum, "<br>");
    document.write(ceilNum, "<br>");
    document.write(rndNum, "<br>");
    document.write(piNum, "<br>");


</script>
Comments