TIL # 2021.10.14

kdobro_dev·2021년 10월 13일
0

TIL (Today I Learned)

목록 보기
8/56
post-thumbnail

Javascript # calculator

📝오늘 배운 내용

오늘은 HTML과 CSS를 활용하여 간단히 계산기의 동작 방식을 확인하고 직접 사용해보는 시간을 가졌다.

우선 CSS를 활용하여 계산기를 내 마음대로 꾸며보았다.

이 과제에서 핵심은 textContent를 어떻게 사용할 수 있는지 확인하는 것 이였다고 생각한다.

function calculate(n1, operator, n2) {
  let result = 0;

  if (operator === '+') {
    result = Number(n1) + Number(n2);
  } 

  if (operator === '-') {
    result = Number(n1) - Number(n2);
  } 

  if (operator === '*') {
    result = Number(n1) * Number(n2);
  }

  if (operator === '/') {
    result = Number(n1) / Number(n2);
  }
  
  return String(result);
}

buttons.addEventListener('click', function (event) {
  // 버튼을 눌렀을 때 작동하는 함수입니다.

  const target = event.target; // 클릭된 HTML 엘리먼트의 정보가 저장되어 있습니다.
  const action = target.classList[0]; // 클릭된 HTML 엘리먼트에 클레스 정보를 가져옵니다.
  const buttonContent = target.textContent; // 클릭된 HTML 엘리먼트의 텍스트 정보를 가져옵니다.
  // ! 위 코드(Line 19 - 21)는 수정하지 마세요.

  if (target.matches('button')) {
    // 클릭된 HTML 엘리먼트가 button이면
    if (action === 'number') {
      // 그리고 버튼의 클레스가 number이면
      // 아래 코드가 작동됩니다.
      if (firstOperend.textContent === '0') {
        firstOperend.textContent = buttonContent;
      } else if (firstOperend.textContent !== '0') {
        secondOperend.textContent = buttonContent;
      }
      console.log('숫자' + buttonContent + '버튼');
    }

    if (action === 'operator') {
      operator.textContent = buttonContent;
      console.log('연산자 ' + buttonContent + ' 버튼');
    }

    if (action === 'decimal') {
      console.log('소수점 버튼');
    }

    if (action === 'clear') {
      firstOperend.textContent = 0;
      secondOperend.textContent = 0;
      calculatedResult.textContent = 0;
      operator.textContent = '+';
      console.log('초기화 버튼');
    }

    if (action === 'calculate') {
      calculatedResult.textContent = calculate(firstOperend.textContent, operator.textContent, secondOperend.textContent);
      console.log('계산 버튼');
    }
  }
});

이 과제를 하면서 내가 배웠던 javascript 기본적은 사항들을 직접 사용해보는 경험을 할 수 있었고, js파일도 HTML과 따로 만들어서 적용 시킬 수 있다는 것을 알게되었다.

profile
do your best at any moment

0개의 댓글