본문 바로가기

JS/JavaScript

[JavaScript] 자바스크립트의 내장 객체 (Math, String, Date객체)

728x90

 

자바스크립트의 내장 객체

Math 객체
- 수학에서 자주 사용하는 상수와 함수들을 미리 구현해 놓음

min()
- 최소값을 반환
- 매개변수가 전달되지 않으면 Infinity를 반환
- 비교할 수 없는 값이 포함되어 있으면 NaN을 반환

max()
- 최소값을 반환
- 매개변수가 전달되지 않으면 -Infinity를 반환
- 비교할 수 없는 값이 포함되어 있으면 NaN을 반환

round()
- 소수점 첫번째 자리에서 반올림하여 반환

floor()
- 소수점 첫번째 자리에서 내림

ceil()
- 소수점 첫번째 자리에서 올림

randon()
- 0보다 크거나 같고 1보다 작은 무작위 소수를 반환

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Math 객체</title>
</head>
<body>
    <h2>Math 객체</h2>
    <script>
        'uise strict';
        // 최소값
        console.log(Math.min()); // 매개변수를 전달하지 않으면 Infinity
        console.log(Math.min(1, 10, -10, 1000, 0)); // 최소값 -10
        console.log(Math.min(1, 10, "-10", 1000, 0)); // 숫자로 형변환이 가능하면 자동 형변환 -10
        console.log(Math.min(1, 10, "마이너스십", 1000, 0)); // 비교할 수 없는 값 NaN

        // 최대값
        console.log(Math.max()); // 매개변수를 전달하지 않으면 -Infinity
        console.log(Math.min(1, 10, -10, 1000, 0)); // 최대값 1000
        console.log(Math.min(1, 10, -10, "1000", 0)); // 숫자로 형변환이 가능하면 자동 형변환 1000
        console.log(Math.min(1, 10, "마이너스십", 1000, 0)); // NaN

        // 반올림
        console.log(Math.round(10.49)); // 10
        console.log(Math.round(10.5)); // 11
        console.log(Math.round(-10.5)); // -10
        console.log(Math.round(-10.51)); // -11
        
        // 소수점 내림
        console.log(Math.floor(10.49)); // 10
        console.log(Math.floor(10.5)); // 10
        console.log(Math.floor(-10.5)); // -11
        console.log(Math.floor(-10.51)); // -11

        // 소수점 올림
        console.log(Math.ceil(10.49)); // 11
        console.log(Math.ceil(10.5)); // 11
        console.log(Math.ceil(-10.5)); // -10
        console.log(Math.ceil(-10.51)); // -10

        // 랜덤값
        const rand = Math.random();
        console.log(rand); 
        console.log(Math.floor(rand * 10) + 1); // 1 ~ 10사이의 자연수


    </script>
</body>
</html>

 

String 객체
- 문자열을 쉽게 만들고 다룰 수 있도록 함

const str = "자바스크립트";
const str = new String("자바스크립트");

length
- 문자열의 길이를 저장하는 프로퍼티

indexOf()
- 매개변수로 전달된 문자열이 처음 등장하는 위치를 반환

charAt()
- 매개변수로 전달된 인덱스에 위치한 문자를 반환

includes()
- 매개변수로 전달된 문자열이 포함되어 있는지 여부를 반환

substring()
- 매개변수로 전달된 시작 인덱스부터 종료 인덱스 바로 앞까지 문자열을 추출
- 매개변수가 1개인 경우 해당 인덱스부터 마지막 인덱스까지 문자열을 추출

substr()
- 매개변수로 전달된 시작 인덱스부터 전달된 갯수만큼 문자열을 추출하여 반환

split()
- 매개변수로 전달된 구분자를 기준으로 문자열을 나눈 후 하나의 배열에 저장

replace()
- 원본 문자열을 매개변수로 전달된 문자열로 치환

trim()
- 문자열의 앞뒤 공백을 제거

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>string 객체</title>
</head>
<body>
    <h2>string 객체</h2>
    <script>
        'use strict';
        const str1 = "안녕하세요. JavaScript";
        console.log(str1);

        console.log(str1.length); // 문자열 길이
        console.log(str1.indexOf('J')); // 해당 문자열의 인덱스 반환
        console.log(str1.indexOf('Java')); // 해당 문자열의 첫글자 인덱스 반환
        console.log(str1.indexOf('java')); // 해당 문자열을 찾지 못할 경우 -1
        console.log(str1.indexOf('a')); // 해당 문자가 여러개이면 앞에 위치한 인덱스 반환
        console.log(str1.lastIndexOf('a')); // 마지막에 위치한 해당문자의 인덱스 반환

        console.log(str1.charAt(7)); // 해당인덱스의 문자 반환

        console.log(str1.includes('Java')); // 해당문자열이 있으면 true, 없으면 false
        console.log(str1.includes('java')); // 해당문자열이 있으면 true, 없으면 false

        console.log(str1.substring(7)); // 7번 인덱스부터 마지막 인덱스
        console.log(str1.substring(7, 11)); // 7번 인덱스부터 11번 인덱스 전까지(10)

        const str2 = "김사과🤤오렌지🤤반하나🤤이메론🤤배애리";
        const student = str2.split('🤤'); // '🤤'를 기준으로 잘라서 배열로 저장
        console.log(student);

        for (let stu in student){
            console.log(stu, student[stu]); // 인덱스와 값을 반환(key, value)
        }

        console.log(str1.replace('안녕하세요', 'Hello')); // '안녕하세요'를 'Hello'로 변환

        const str3 = '          JavaScript          ';
        console.log(`😑${str3}😑`);
        console.log(`😑${str3.trim()}😑`); // 공백제거


    </script>
</body>
</html>

 

 

 

Date 객체
- 날짜, 시간 등을 쉽게 다룰 수 있는 객체

    const date = new Date(); // 현재 날짜 시간
    const date = new Date(21, 11, 30); // 1921년 12월(0 ~ 11월) 30일
    const date = new Date(2021, 11, 30); // 2021년 12월 30일


연도(year)
- 두자리로 표현 : 1900 ~ 1999
- 네자리로 표현 : 2000 ~

월(month)
- 범위 : 0 ~ 11(1월 ~ 12월)

Date 객체 생성
const date = new Date(); // 현재 날짜 시간
const date = new Date(2021, 11, 30);
const date = new Date("2021-11-30");
const date = new Date("389232942"); // timestamp
const datetime = new Date(2021, 11, 1, 12, 30, 0, 0);

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Date 객체</title>
</head>
<body>
    <h2>Date 객체</h2>
    <script>
        'use strict';
        console.log(new Date);

        console.log(new Date(21, 11, 30)); // 1921년 12월 30일
        console.log(new Date(21, 12, 30)); // 1922년 1월 30일(연도 + 1)
        
        console.log(new Date(2021, 11, 30)); // 2021년 12월 30일

        console.log(new Date(1650000000000));
        
        const date = new Date();
        console.log(`현재 년도 : ${date.getFullYear()}`);
        console.log(`현재 월 : ${date.getMonth()}`);
        console.log(`현재 일 : ${date.getDate()}`);
        console.log(`현재 시간 : ${date.getHours()}`);
        console.log(`현재 분 : ${date.getMinutes()}`);
        console.log(`현재 초 : ${date.getSeconds()}`);

    </script>
</body>
</html>

 

 

window 객체
- 현재 웹브라우저의 창이나 탭을 표현하기 위한 객체

setTimeout()
- 일정 시간이 지난 후 매개변수로 제공된 함수를 실행

    function 함수명() {
        ...
    }

    const 함수명 = setTimeout(함수명, 시간);

clearTimeout()
- setTimeout()에서 실행된 함수를 취소

    clearTimeout(상수명);

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>setTimeout</title>
</head>
<body>
    <h2>setTimeout</h2>
    <script>
        'use strict';
        function hello() {
            alert('안녕하세요 여러분!');
        }

        const st = window.setTimeout(hello, 2000); // 함수자체를 매개변수로 보낼때에는 메소드명만 적음. 바로 실행할 때에는 ()포함.
        window.clearTimeout(st); // 함수 실행 취소
        
    </script>
</body>
</html>

문제.
시간을 출력하는 프로그램을 작성
(단, 콘솔에 출력, 1초마다)

[시작] [멈춤]

15 : 54 : 00
15 : 54 : 01
15 : 54 : 02
15 : 54 : 03
..
15 : 56 : 00

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>시계만들기</title>
</head>
<body>
    <h2>시계만들기</h2>
    <p>
        <input type="button" value="시작" onclick="startTime()">
        <input type="button" value="중지" onclick="stopClock()">
    </p>
    <div id="result"></div>
    <script>
        'use strict';

        let timeId = null;

        function printTime() {
            const date = new Date();
            const hh = date.getHours();
            const mm = date.getMinutes();
            const ss = date.getSeconds();

            document.getElementById("result").innerHTML = hh + " : " + mm + " : " + ss; // id가 result인 객체를 가져와서 html 작성
        }

        function startTime() {
            timeId = setInterval(printTime, 1000);
        }

        function stopClock() {
            window.clearInterval(timeId);
        }

        timeId = setInterval(printTime, 1000);


    </script>

</body>
</html>

 

 

728x90