if (action === "number") {
// 버튼의 클래스가 number이면
// 아래 코드가 작동됩니다.
if (firstOperend.textContent !== "0") {
secondOperend.textContent = buttonContent;
} else {
firstOperend.textContent = buttonContent;
}
}
buttonContent
에는 클릭한 엘리먼트의 텍스트 정보가 담겨있다.
(ex. 숫자 3버튼을 클릭하면 buttonContent
의 값은 '3'이다.)
따라서 눌린 버튼의 클래스가 "number
"일때,
첫 번째 숫자칸(firstOperand
)이 0이 아니라면
두 번째 숫자칸(secondOperand
)에buttonContent
를 넣어주고,
그 외에는 첫 번째 숫자칸이 0이라는 의미니까
첫 번째 숫자칸에 buttonContent
를 넣어준다.
if (action === "operator") {
operator.textContent = buttonContent;
}
operator
(연산자 기호)를 클릭할 시에도 동일하게 작동하도록 한다. if (action === "calculate") {
if (firstOperend.textContent !== 0 && secondOperend != 0) {
calculatedResult.textContent = calculate(
Number(firstOperend.textContent),
operator.textContent,
Number(secondOperend.textContent)
);
}
}
Enter버튼 클릭 시,
만약 두 개의 숫자칸이 0이 아니라면
calculate(n1, operator, n2)
함수를 호출한다.
인자
firstOperand.textContent
)secondOperend.textContent
)calculate(n1, operator, n2)
함수
function calculate(n1, operator, n2) {
let result = 0;
// ex) 입력값이 n1 : '1', operator : '+', n2 : '2' 인 경우, 3이 리턴됩니다.
if (operator === "+") {
result = n1 + n2;
} else if (operator === "-") {
result = n1 - n2;
} else if (operator === "*") {
result = n1 * n2;
} else {
//if operator === '/'
result = n1 / n2;
}
return String(result);
}
if (action === "clear") {
console.log("초기화 버튼");
firstOperend.textContent = 0;
operator.textContent = "+";
secondOperend.textContent = 0;
calculatedResult.textContent = 0;
}
AC버튼 클릭 시,
첫 번째 숫자칸, 두 번째 숫자칸 그리고 연산 결과 출력칸(calculatedResult
)의 텍스트를 전부 0으로 바꿔준다.
operator
(연산자 기호) 역시 초기 설정인 '+'로 바꿔줌.
bare minimum test 통과 完!