연산자 (Operator)
산술 연산자 + 계산기 만들기
+, -, *(곱하기), /(나누기), %(modulo 또는 mod : 나머지 연산자)<div class="calculator"> <div class="row"> <label for="input1">첫 번째 값 : </label> <input type="number" id="input1"> </div> <div class="row"> <label for="input2">두 번째 값 : </label> <input type="number" id="input2"> </div> <div class="row btn-row"> <!-- 버튼 클릭 시 plusFn() 함수 호출(실행) --> <button onclick="plusFn()">+</button> <button onclick="minusFn()">-</button> <button onclick="multiFn()">*</button> <button onclick="divFn()">/</button> <button onclick="modFn()">%</button> </div> <div class="row"> <h2>결과 : <span id="calcResult">0</span> </h2> </div> </div>// 변수 선언 // document : HTML 문서 내에서 // get : 얻다 // Element : HTML 요소 // ById : 아이디로 (아이디가 일치하는) const number1 = document.getElementById("input1"); // console.log(number1); const number2 = document.getElementById("input2"); const result = document.getElementById("calcResult"); // 두 수를 더해서 화면에 출력하는 함수 function plusFn() { // input요소.value : input 요소에 작성된 값 얻어오기 const value1 = number1.value; const value2 = number2.value; // -> input 요소에 작성된 값은 무조건 문자열 (String)형태라서 // 더했을 때 이어쓰기 되는 문제 발생 console.log(value1 , value2); // 10 20 console.log(value1 + value2); // 1020 // [해결방법] // 문자열을 숫자로 변경하는 코드를 수행 // 숫자만 작성된 문자열("123")을 // 진짜 숫자타입으로 바꾸는 방법 // -> Number("123"); --> 123 console.log(Number(value1) + Number(value2)); // 두 수의 합을 // 아이디가 "calcResult"인 요소 (result 변수)의 // 내부 글자 (innerText, HTML 요소의 content)로 대입하기 result.innerText = Number(value1) + Number(value2); } // 빼기 함수 function minusFn() { const value1 = Number(number1.value); const value2 = Number(number2.value); result.innerText = value1 - value2; } // 곱하기 함수 function multiFn() { const value1 = Number(number1.value); const value2 = Number(number2.value); result.innerText = value1 * value2; } // 나누기 function divFn() { const value1 = Number(number1.value); const value2 = Number(number2.value); result.innerText = value1 / value2; } // 나머지 구하는 함수 function modFn() { const value1 = Number(number1.value); const value2 = Number(number2.value); result.innerText = value1 % value2; }연습문제
입력 받은 3개의 수 합계 출력하기<div> <input type="number" id="num1"> <input type="number" id="num2"> <input type="number" id="num3"> <button type="button" onclick="totalFn()"> 3개 더하기 </button> <h3>결과 : <span id="total"></span></h3> </div># JS // 연습문제 const num1 = document.getElementById("num1"); const num2 = document.getElementById("num2"); const num3 = document.getElementById("num3"); const total = document.getElementById("total"); function totalFn() { const value1 = Number(num1.value); const value2 = Number(num2.value); const value3 = Number(num3.value); total.innerText = value1 + value2 + value3; }
입/출금 하기
prompt(내용) : 문자열을 작성할 수 있는 알림창
- 확인 버튼 클릭 시 : 입력한 값 반환
- 취소 버튼 클릭 시 : null 값 반환
변수 선언 및 대입
- const amount = [빈칸 작성]; // 금액 입력 input
- let balance = 10000; // 잔액 기록 변수 (초기값 10000)
- const password = '1234'; //비밀번호 저장 변수(초기 비밀번호 1234)함수 작성 1. 입금 -> function deposit(){} * 입금 버튼 클릭 시 input에 입력된 금액 만큼 잔액(balance)에 추가 2. 출금 -> function withdrawal(){} * 출금 버튼 클릭 시 prompt를 이용해 비밀번호를 입력 받기 * 비밀번호가 일치할 경우 1) 출금할 금액이 잔액(balance) 보다 큰 경우 -> alert("출금 금액이 잔액보다 클 수 없습니다") 출력 2) 출금할 금액이 잔액(balance) 보다 작거나 같은 경우 -> 잔액(balance)에서 출금 금액만큼 감소 시킨 후 alert("OOO원이 출금 되었습니다. 남은 잔액 : OOO원") 출력 * 비밀번호가 일치하지 않을 경우 -> alert("비밀번호가 일치하지 않습니다") 출력<button onclick="test()">연습용 출금 버튼</button># JS // prompt 사용 연습 function test() { const password = prompt("비밀번호를 입력하세요"); console.log(password); // 확인 -> 입력한 값이 문자열로 저장 // 취소 -> null if(password == null) { // 취소버튼 alert("취소"); } else { // 확인버튼 if(password == '1234') { alert("비밀번호 일치"); } else { alert("비밀번호 불일치!"); } } }<div class="account"> <div class="row"> <h1>잔액 : <span id="output"></span> 원</h1> </div> <div class="row input-row"> <label for="amount">금액 : </label> <input type="text" id="amount"> <span>원</span> </div> <div class="row btn-row"> <button class="deposit-btn" onclick="deposit()">입금</button> <button class="withdrawal-btn" onclick="withdrawal()">출금</button> </div> </div># CSS .account, .account * { margin: 0; padding: 0; box-sizing: border-box; } .account{ border: 5px solid grey; border-radius: 20px; padding : 10px 50px; width: 500px; margin: 200px auto; } .account .row{ display: flex; margin: 20px 0; padding: 20px 0; } .account .row:not(:last-of-type){ border-bottom: 3px solid grey; } .row > h1{ width: 100%; display: flex; justify-content: space-between; } #output{ flex-grow: 1; text-align: right; padding: 0 20px; } .input-row > label, .input-row > span{ font-size: 1.5em; padding: 10px; flex-grow: 1; } .input-row > input{ flex-grow: 1; padding: 10px; font-size: 24px; font-weight: bold; text-align: right; width: 60%; outline: none; border : none; border-bottom: 2px solid grey; } .input-row > input:focus{ border-color: purple; color: purple; } .btn-row{ height: 100px; } .btn-row > button{ flex-grow: 1; margin: 0 30px; border : 5px solid black; border-radius: 10px; background-color: white; font-size: 28px; font-weight: bold; cursor: pointer; transition-duration: 0.1s; } /* 입금 버튼 */ .deposit-btn{ border-color: green !important; color: green; } .deposit-btn:hover{ color: white; background-color: green; } /* 출금 버튼 */ .withdrawal-btn{ border-color: red !important; color: red; } .withdrawal-btn:hover{ color: white; background-color: red; } .btn-row > button:active{ opacity: 0.7; }# JS const output = document.getElementById("output"); // 잔액 출력 span const amount = document.getElementById("amount") // 금액 작성 input let balance = 10000; // 잔액 기록 변수 (초기값 10000) const pw = '1234'; // 비밀번호 저장 변수 (비밀번호 1234) output.innerText = balance; // 초기 금액 화면 출력 // 입금 함수 function deposit() { // input에 입력된 금액 구하기 console.log(amount.value.length); if(amount.value.length == 0) { alert("금액을 입력해주세요"); } else { // 구한 금액을 잔액(balance)에 누적 balance += Number(amount.value); // balance = balance + Number(amount.value); output.innerText = balance; // 화면에 잔액 업데이트 amount.value = ''; } } // 출금 함수 function withdrawal() { if(amount.value.length == 0) { alert("금액을 입력해주세요"); } else { const password = prompt("비밀번호를 입력하세요."); if(password == null) { // 취소버튼 alert("취소"); } else { // 확인버튼 // 비밀번호가 일치하지 않는 경우 if(password != pw) { alert("비밀번호가 일치하지 않습니다."); } else { const money = Number(amount.value); if(money > balance) { // 출금할 금액이 잔액보다 큰 경우 alert("출금 금액이 잔액보다 클 수 없습니다"); } else { // 출금할 금액이 잔액보다 작거나 같은 경우 balance -= money; // balance = balance - money; output.innerText = balance; amount.value = ''; // alert(money + "원이 출금되었습니다. 남은 잔액: " + balance); alert(`${money}원이 출금되었습니다. 남은 잔액 ${balance}`); // 템플릿 리터럴 (Template Literal) // 백틱(``)을 사용하여 문자열을 감싸고, // ${} 안에 변수를 넣어 동적으로 문자열을 생성하는 방식 } } } } }