오늘 드디어 계산기 어드밴스드를 풀었다. 베어 미니멈을 어제 풀고 해봐서 그런지 크게 어렵진 않았다. 새롭게 배운 개념이라면 변수의 재할당.
if (target.matches('button')) {
if (action === 'number') {
if (display.textContent === '0' || previousKey === 'operator') {
display.textContent = buttonContent;
} else {
display.textContent += buttonContent;
}
previousKey = 'number';
}
디스플레이에 단독으로 뜨는 경우는 이전 디스플레이가 0이거나 연산자를 눌렀을 때.
뒤에 이어붙는 경우는 숫자일때다. 이때 관건은 연산자를 눌렀을 때를 어떻게 설정하는가이다. 첫번째 if문을 보면 previousKey === 'operator'
이렇게 변수를 불러온다. 이 변수가 할당된 건 밑에 연산자 부분에서 확인할 수 있다.
if (action === 'operator') {
firstNum = display.textContent;
operatorForAdvanced = buttonContent;
previousKey = 'operator'
}
그러니까 연산자가 실행되면 변수 previousKey
에 'operator'
가 할당되어 위에 숫자버튼을 눌렀을 때에 이 변수를 사용하면서 조건문을 만들 수 있다.
그리고 가장 헤맸던 부분은 그렇다면 previouskey
에 'number'
는 언제 재할당해줘야 하는 것인가였다.
*내가 작성한 코드
if (target.matches('button')) {
if (action === 'number') {
previousKey = 'number';
if (display.textContent === '0' || previousKey === 'operator') {
display.textContent = buttonContent;
} else {
display.textContent += buttonContent;
}
}
previouskey
재할당을 if문 바로 밑에 작성해줬는데, 이렇게 하다보니 밑에 'operator'
가 들어간 조건이 실행되지 않는 문제가 생겼다.
결론; 변수의 선언, 재할당, 재선언에 대하여
세 가지를 구분해서 사용할 수는 있지만, 정확히 어떨 때 사용해야 하는지는 좀더 공부해야할 것 같다.
const calculator = document.querySelector('.calculator')
let result = '';
if (action === 'operator') { firstNum = display.textContent; operatorForAdvanced = buttonContent; previousKey = 'operator' }