[TIL] To Do List 생성 기초 실습

신재욱·2023년 3월 2일
0
post-thumbnail

📒 오늘 공부한 내용

🔍수업목차

[13-1] 스크립트 태그의 위치
[13-2] JS로 HTML, CSS 조작
[13-3] 반복문이란?
[13-4] 반복문 활용
[13-5] interval 적용
[13-6] 함수의 인자와 매개변수
[13-7] 브라우저의 저장소

✅ 반복문


반복문 은 반복적인 코드의 양을 획기적으로 압축하고 반복적인 일의 수행을 효율적으로 처리 할 수 있도록 도와준다.

for문의 생김새

for(최초식; 조건식; 증감문){
---------> 반복을 수행할 코드
}

while문의 생김새

  • 종료조건을 제대로 설정하지 않으면 무한 반복
최초식
while( 조건식 ){
---------> 반복을 수행할 코드
	증감식
}

for-of

const arr = [1, 2, 3, 4, 5]

for(let i of arr) {
    console.log(el)
}

for-in

const obj = {
    name : "otter",
    gender : "male"
}

for(let key in obj) {
    console.log(key)
}

setInterval

  • setInterval() 함수는 반복 함수
  • 소괄호 안에 넣어준 함수를 지정한 시간마다 반복해서 실행해 준다.
    MDN

clearInterval

  • clearInterval() 함수는 setInterval() 함수를 통해 생성된 interval을 종료해주는 함수
  • setInterval 함수는 실행될 때마다 고유의 id 값을 반환
  • 해당 아이디를 체크해서 clearInterval() 함수를 실행할 때, 그 아이디를 소괄호 안에 넣고 실행해주면 반복 실행하던 interval이 종료됩니다.

✅ 전달인자, 매개변수


변수의 참조 영역

  • 자바스크립트의 함수, 변수 는 정의되어 있는 영역 안에서만 존재하게 된다.
  • 그렇기 때문에 함수 안에서 선언된 변수는 그 밖에서 참조될 수가 없다.

  • 위 사진의 confined 변수는 박스로 감싸진 해당 영역 내부에 속해 있기 때문에
    박스 바깥에서 confined 변수를 참조하고 있는 console.log() 명령어는 해당 변수에 접근이 불가능

매개변수

  • 함수는 데이터를 밖으로 건네주는 것 뿐만 아니라, 외부의 데이터를 받아온 후 가공, 혹은 로직을 수행하는 것도 가능하다.
  • 이때, 사용하게 되는 개념이 바로 매개변수다.

  • 매개변수는 해당 함수 내부에서만 존재 하게 된다.
  • 그리고 매개변수 또한 하나의 변수이기 때문에 그 안에 담긴 데이터를 참조할 수도 있다.

전달인자

  • 매개변수를 함께 정의해줬다면 함수를 호출하는 과정에서 전달인자 를 건네줄 수 있다.

  • 전달인자 1, 2가 매개변수인 one과 two에 담기게 된다.

  • 이때, 전달인자를 담아주는 순서 에 의해서 매개변수에 담길 값 이 정해진다.

  • 전달인자와 매개변수를 사용한다면 함수라고 하는 도구의 재사용성이 높아진다.

✅ 브라우저의 Web Storage


웹 브라우저에서 어떠한 로직에 활용되는 데이터를 유지시키고자 한다면, 해당 데이터를 저장할 공간이 필요하다.
웹 브라우저는 Web Storage라고 하는 저장소를 제공 하는데, seesionStoragelocalStorage 를 활용할 수 있다.

sessionStorage

  • 데이터를 세션 단위로 저장한다.
  • 여기서 이야기하는 세션사용자가 페이지에 접속하는 순간부터 접속이 끊어지는 순간까지 를 이야기한다.
  • 브라우저를 종료하게 되면 해당하는 세션 저장소의 데이터를 영구히 삭제 해 버린다.

localStorage

  • locaStorage는 비휘발성 메모리이기 때문에 저장된 데이터가 브라우저, pc를 종료하더라도 그대로 남아있게 된다.

✅ local storage 접근 방법


localStorage.setItem()

  • localStorage는 window.localStorage로 접근할 수 있다.

  • 데이터를 저장할 때는 localStorage에 내장되어 있는 setItem이라는 메서드 를 사용하면 된다.

    localStorage.setItem('data-key', 'data-value')
  • 첫번째 인자로 key 를, 두번째 인자로 value, 저장할 데이터를 담아주면 된다.

localStorage.getItem()

  • localStorage에 존재하는 데이터를 꺼내올 수 있다.

    localStorage.getItem(’data-key’)

📌 오늘 실습 결과


이미지

JavaScript

const messageContainer = document.querySelector('#d-day-message');
const container = document.querySelector('#d-day-container');
const savedDate = localStorage.getItem('saved-date');

const intervalIdArr = [];

container.style.display = 'none';
messageContainer.innerHTML = '<h3>D-Day를 입력해 주세요.</h3>';


const dateFormMaker = function () {
    const inputYear = document.querySelector("#target-year-input").value;
    const inputMonth = document.querySelector("#target-month-input").value;
    const inputDate = document.querySelector("#target-date-input").value;

    const dateFormat = `${inputYear}-${inputMonth}-${inputDate}`;
    return dateFormat;
};

const counterMaker = function (date) {
    if (date !== savedDate) {
        localStorage.setItem('saved-date', date);
    }
    const messageContainer = document.querySelector('#d-day-message');
    messageContainer.textContent = 'D-Day를 입력해 주세요.';
    const targetDateInput = dateFormMaker();
    const nowDate = new Date();
    const targetDate = new Date(date).setHours(0, 0, 0, 0);
    const remaining = (targetDate - nowDate) / 1000;
    if (remaining <= 0) {
        container.style.display = 'none';
        messageContainer.innerHTML = '<h3>타이머가 종료되었습니다.</h3>';
        messageContainer.style.display = 'flex';
        setClearInterval();
        return;
    } else if (isNaN(remaining)) {
        container.style.display = 'none';
        messageContainer.innerHTML = '<h3>유효한 시간대가 아닙니다.</h3>';
        messageContainer.style.display = 'flex';
        setClearInterval();
        return;
    }

    const remainingObj = {
        remainingDate: Math.floor(remaining / 3600 / 24),
        remainingHours: Math.floor(remaining / 3600) % 24,
        remainingMin: Math.floor(remaining / 60) % 60,
        remainingSec: Math.floor(remaining) % 60
    }

    const format = function (time) {
        if (time < 10) {
            return '0' + time;
        } else {
            return time;
        }
    }

    const documentObj = {
        days: document.getElementById('days'),
        hours: document.getElementById('hours'),
        min: document.getElementById('min'),
        sec: document.getElementById('sec')
    };

    const timeKeys = Object.keys(remainingObj);
    const docKeys = Object.keys(documentObj);

    for (let i = 0; i < timeKeys.length; i = i + 1) {
        const remainingTime = format(remainingObj[timeKeys[i]]);
        documentObj[docKeys[i]].textContent = remainingTime;
    };

};

const starter = function (targetDateInput) {
    if (!targetDateInput) {
        targetDateInput = dateFormMaker();
    }
    container.style.display = 'flex';
    messageContainer.style.display = 'none';
    setClearInterval();
    counterMaker(targetDateInput);
    const intervalId = setInterval(() => { counterMaker(targetDateInput); }, 1000);
    intervalIdArr.push(intervalId)
};

const setClearInterval = function () {
    localStorage.removeItem('saved-date');
    for (let i = 0; i < intervalIdArr.length; i++) {
        clearInterval(intervalIdArr[i]);
    }
}

const resetTimer = function () {
    container.style.display = 'none';
    messageContainer.innerHTML = '<h3>D-Day를 입력해 주세요.</h3>';
    messageContainer.style.display = 'flex';
    setClearInterval()
}

if (savedDate) {
    starter(savedDate);
} else {
    container.style.display = 'none';
    messageContainer.innerHTML = '<h3>D-Day를 입력해 주세요.</h3>';
}
profile
1년차 프론트엔드 개발자

0개의 댓글

관련 채용 정보