[WEB FRONT] TIL 038 - 23.09.06

유진·2023년 9월 6일
0

JAVA SCRIPT

08_문자열,숫자,형변환,연산자.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>08_문자열,숫자,형변환,연산자</title>
</head>
<body>
    <h2>문자열(string 내장 객체)</h2>
    <pre>
        자바스크립트에는 문자열 나타내는 객체(String)가 존재하며
        문자열과 관련된 기본적인 함수를 제공해준다.
    </pre>

    <button id="btn1">문자열 관련 함수(콘솔확인)</button>



    <hr>

    <h2>숫자(Math 내장 객체)</h2>
    <pre>
        숫자(number) 타입 리터럴 표기법 :
        12(정수), 3.14(실수), Infinity(무한), NaN(Not a Number)

        Math : 숫자 관련 함수를 제공하는 JS 내장 객체
        ex) Math.random() : 난수
    </pre>

    <button id="btn2">숫자 관련 함수(콘솔확인)</button>

    <script src="js/08_문자열,숫자,형변환,연산자.js"></script>
</body>
</html>

08_문자열,숫자,형변환,연산자.js

// 문자열 관련함수(가장 많이 사용됨)
document.getElementById("btn1").addEventListener("click", function() {

    // 문자열.indexOf("str") :
    // 문자열에서 "str"과 일치하는 부분이 시작되는 인덱스를 반환
    // 없으면 -1반환

    const str1 = "Hello World";

    console.log(  str1.indexOf("e")  ); // 1
    console.log(  str1.indexOf("l")  ); // 2 (가장 먼저 검색된 인덱스 반환)
    console.log(  str1.indexOf("가")  ); // -1


    // 문자열.substring(시작인덱스, 종료인덱스) : 문자열 일부 잘라내기
    // - 시작인덱스 이상 종료인덱스 미만
    const str2 = "abcdefg";

    console.log(  str2.substring(0, 3)  ) // abc
    console.log(  str2.substring(2, 6)  ) // cdef


    // 문자열.split("구분자") : 문자열을 "구분자"로 잘라서 배열로 반환
    const str3 = "햄버거, 피자, 김밥, 파스타, 삼겹살";
    const arr = str3.split(", "); // 띄어쓰기까지 포함한 것 -> 구분자!
    console.log(arr); // ['햄버거', '피자', '김밥', '파스타', '삼겹살']
});

// 숫자 관련 함수
document.getElementById("btn2").addEventListener("click", function() {

    // Infinity 리터럴 확인
    console.log( 5 / 0 ); // Infinity

    if(5/0 == Infinity) {
        console.log("무한 입니다"); // 무한 입니다
    }

    // NaN 리터럴 확인
    console.log( "aaa" * 100 ); // NaN

    // "aaa" * 100 == NaN (X)

    // isNaN(값) : 값이 NaN이면 true, 아니면 false

    if( isNaN("aaa" * 100) ) {
        console.log("숫자가 아닙니다"); // 숫자가 아닙니다
    }


    // Math.random() : 0 이상 1 미만의 난수 발생 (0 <= random < 1)
    console.log(Math.random());

    // 소수점 관련 함수
    // round(), ceil(), floor(), trunc()
    // 반올림    올림    내림      버림

    // -> 소수점 자리를 지정할 수 없다.

    console.log( Math.round(10.555) ); // 11
    console.log( Math.ceil(10.555) ); // 11
    console.log( Math.floor(10.555) ); // 10
    console.log( Math.trunc(10.555) ); // 10


    // 버튼 배경색 랜덤으로 바꾸기

    const r = Math.floor(Math.random() * 256)  // 0~255
    const g = Math.floor(Math.random() * 256)  // 0~255
    const b = Math.floor(Math.random() * 256)  // 0~255

    this.style.backgroundColor = "rgb(" + r + "," + g + "," + b + ")"

    // 숫자.toFixed(자릿수) : 지정된 자릿수 까지 반올림해서 표현
    console.log( (3.55).toFixed(1) ); // 3.5 ?
    console.log( (3.55).toFixed(2) ); // 3.55

});


// 형변환 확인
// parseInt() : 정수로 변환함 ("3.14" -> 3)
console.log( parseInt("3.14") ); // 3
console.log( typeof parseInt("3.14") ); // number

// parseFloat() : "정수" -> 정수, "실수" -> 실수
console.log( parseFloat("3.14") ); // 3.14
console.log( typeof parseFloat("3.14") ); // number


문자열 관련 함수(콘솔확인) 버튼 클릭 시,

숫자 관련 함수(콘솔확인) 버튼 클릭 시,
VSCode Go Live 실행 시 콘솔 화면

09_배열.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>09_배열</title>
</head>
<body>
    <h1>배열(Array)</h1>
    <pre>
        배열 : 변수를 묶음으로 다루는 것(변수가 연속적으로 나열됨)

        JS 배열의 특징
        1. 자료형 제한 X
        2. 길이 제한 X
        ( == 자바 Collection List와 비슷 )
    </pre>

    <button id="btn1">배열 확인1(콘솔)</button>

    <hr>

    <h3>배열 관련 함수</h3>

    <pre>
        push() : 배열 마지막 요소로 추가
        pop() : 배열 마지막 요소를 꺼내옴

        배열.indexOf("값") : 일치하는 값을 가진 요소의 index 반환, 없으면 -1 반환

        배열.sort([정렬기준 함수]) : 배열 내 요소를 오름차순 정렬(문자열)
                            단, [정렬 기준 함수]가 작성되면 정렬결과가 달라짐

        배열.toString() : 배열 요소를 하나의 문자열로 출력
                    -> 요소 사이에 "," 추가

        배열.join("구분자") : 배열요소를 하나의 문자열로 출력
                    -> 요소 사이에 "구분자" 추가
    </pre>


    <button id="btn2">배열 확인2 (콘솔)</button>

    <script src="js/09_배열.js"></script>
</body>
</html>

09_배열.js

// 배열확인 1
document.getElementById("btn1").addEventListener("click", function() {

    // 배열 선언 방법
    const arr1 = new Array(3); // 3칸짜리 배열 생성
    const arr2 = new Array(); // 0칸짜리 배열(비어있는 배열) 생성

    // 다른 자료형 대입
    arr1[0] = "김밥";
    arr1[1] = 123;
    arr1[2] = true;
    console.log(arr1); // ['김밥', 123, true]

    // 0칸짜리 배열 대입 -> 자동으로 길이 증가
    arr2[0] = "김밥";
    arr2[1] = 123;
    arr2[2] = true;
    console.log(arr2); // ['김밥', 123, true]

    // 배열 선언 방법
    const arr3 = []; // 비어있는 배열(0칸)
    const arr4 = ["사과", "딸기", "바나나"]; // 배열 선언과 동시에 초기화

    // for문으로 배열 요소 반복 접근하기
    // 1. 일반 for문
    // 2. 향상된 for문 (for...of) : 배열용 향상된 for문
    for(let item of arr4) {
        console.log(item);
    }
});

// 배열 확인 2
document.getElementById("btn2").addEventListener("click", function() {

    // 비어있는 배열 생성
    const arr = [];

    // push() : 배열 마지막 요소로 추가
    arr.push("삼겹살");
    arr.push("곱창");
    arr.push("초밥");
    arr.push("쌀국수");

    console.log(arr); // ['삼겹살', '곱창', '초밥', '쌀국수']

    // pop : 마지막 요소 꺼내오기
    console.log( "꺼내온 요소 : " + arr.pop() ); // 꺼내온 요소 : 쌀국수
    console.log( arr ); // ['삼겹살', '곱창', '초밥']

    // 배열.indexOf("값") : 일치하는 값을 가진 요소의 index 반환
    console.log( "초밥 인덱스 : " + arr.indexOf("초밥") ); // 초밥 인덱스 : 2
    console.log( "갈비 인덱스 : " + arr.indexOf("갈비") ); // 갈비 인덱스 : -1


    // 배열.sort([정렬기준함수]) : 배열 내 요소를 오름차순 정렬(문자열)
    const arr2 = [5, 3, 2, 10, 1];

    console.log( arr.sort() ); // ['곱창', '삼겹살', '초밥']
    console.log( arr2.sort() ); // [1, 10, 2, 3, 5]

    // 숫자 오름 차순 정렬
    console.log(  arr2.sort( function(a,b) {return a-b; } )  ); // 오름차순 [1, 2, 3, 5, 10]
    console.log(  arr2.sort( function(a,b) {return b-a; } )  ); // 내림차순 [10, 5, 3, 2, 1]


    // 문자열로 출력
    console.log( arr.toString() ); // 곱창,삼겹살,초밥
    console.log( arr.join("/") ); // 곱창/삼겹살/초밥
});


배열 확인1(콘솔) 버튼 클릭 시,

배열 확인2(콘솔) 버튼 클릭 시,

10_Window내장객체.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>10_Window내장객체</title>

    <style>
        #clock {
            border: 1px solid black;
            width: 300px;
            height: 100px;

            display: flex;
            justify-content: center;
            align-items: center;

            font-size: 50px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h1>window 객체</h1>
    <pre>
        - 브라우저 창 자체를 나타내는 객체

        - window 객체는 자바스크립트의 최상위 객체이며
        DOM, BOM 으로 분류된다.

        DOM(Document Object Model) : document
        BOM(Browser Object Model) : location, history, screen, navigator

        * window 객체는 창 자체를 나타내고 있으므로
        어디서든 접근이 가능하다.
        그래서 window 라는 객체 호출부를 생략할 수 있다.
        ex) window.alert() == alert()
    </pre>


    <hr>

    <h2>window.setTimeout(함수, 지연시간(ms))</h2>
    <p>지연시간 후 함수가 '1회' 실행</p>

    <button id="btn1">setTimeout 확인</button>


    <hr>

    <h2>window.setInterval(함수, 지연시간(ms))</h2>
    <p>지연시간 마다 함수 실행</p>

    <div id="clock">10 : 41 : 19</div>


    <h2>window.clearInterval(setInterval이 저장된 변수)</h2>
    <button id="stop">STOP</button>


    
    <script src="js/10_Window내장객체.js"></script>
</body>
</html>

10_Window내장객체.js

// window.setTimeout()
document.getElementById("btn1").addEventListener("click", function() {

    setTimeout( function() {
        alert("3초 후 출력!")
    }, 3000); // 3000ms = 3초
});


// window.setInterval()
let interval; // setInterval을 저장하기 위한 전역 변수

// 현재 시간 문자열로 반환 함수
function currentTime() {
    const now = new Date();

    let hour = now.getHours(); // 시
    let min = now.getMinutes(); // 분
    let sec = now.getSeconds(); // 초

    if(hour < 10) hour = "0" + hour;
    if(min < 10) min = "0" + min;
    if(sec < 10) sec = "0" + sec;

    return hour + " : " + min + " : " + sec;
}

function clockFn() {
    const clock = document.getElementById("clock");
    clock.innerText = currentTime();

    interval = setInterval(function() {
        clock.innerText = currentTime();
    }, 1000);
}

clockFn(); // 함수호출

// clearInterval
document.getElementById("stop").addEventListener("click", function() {
    clearInterval(interval);
});

// stop 버튼 2번째 누르면 시간이 다시 돌아감.
document.getElementById("stop").addEventListener("click", function() {
    clockFn();
});


setTimeout 확인 버튼 클릭 시, 3초 후 출력되는 알림창

STOP 버튼 1번째 클릭 시, 멈춤 +
STOP 버튼 2번째 클릭 시, 다시 동작

0개의 댓글