9일차

JiHun·2023년 4월 21일

부트캠프

목록 보기
9/56

💼간단한 웹앱 만들기

이름만 간단한 계산기 만들어보자.

🗂️구조

script.js파일을 따로 만들어 거기서 Javascript가 굴러가게 만들어야지.

  • 숫자들은 button 형식이며 class는 "number"를 가지고 있다.
  • 연산자의 class는 operator
  1. 버튼을 눌렀을 때, 디스플레이 화면에 띄운다.
  2. operator를 누르면 앞에 입력했던 숫자가 사라지며 사칙연산 기호가 나오고 그 다음으로 연산을 할 숫자가 나온다.
  3. enter 버튼을 눌렀을 때, 연산이 되며 결과값이 나온다.

🗂️JavaScript

const display = document.querySelector(".calculator__display--for-advanced");
let firstNum = "",
  operatorForAdvanced,
  previousKey,
  previousNum;

buttons.addEventListener("click", function (event) {
  
  const target = event.target; 
  const action = target.classList[0];
  const buttonContent = target.textContent;

  if (target.matches("button")) {
    if (action === "number") {
      if (display.textContent === "0") {
        display.textContent = target.textContent;
      } else {
        display.textContent += target.textContent;
      }
      if (previousKey === "operator") {
        display.textContent = "";
        display.textContent += target.textContent;
      }
      previousKey = "number";
    }
    if (action === "operator") {
      firstNum = display.textContent;
      operatorForAdvanced = buttonContent;
      display.textContent = buttonContent;
      previousKey = "operator";
    }
    if (action === "decimal") {
    }
    if (action === "clear") {
      firstNum = "";
      operatorForAdvanced = "";
      display.textContent = 0;
    }
    if (action === "calculate") {
      display.textContent = calculate(firstNum, operatorForAdvanced, display.textContent);
      previousKey = "calculate";
    }
  }
});

display가 0일때는 그냥 display에만 보여주고, 0이 아닐 때만 display에 추가 해준다.
같은 버튼들이지만 눌렀을 때, 버튼의 클래스를 구분하여 if문을 작성한다.
사칙연산을 해야하기 때문에 firstNumoperatorForAdvanced, display.textContent를 잘 분리해야 한다.
display에 띄우는 것과 사칙연산에 필요한 것들을 잘 분리 해야한다.

🔥마지막으로

나는 부족하다. 너무 한 곳에 집중하면 매몰 되어 버린다. 넓게 보는 시야가 부족하다. 하나 코드 고치면 다른 코드에서 터지고 다른 코드 고치면 또 다른 코드에서 터지고 넓게 보고 차근차근해야겠다.

profile
안녕하세요. 프론트엔드 개발자 송지훈입니다.

0개의 댓글