728x90
1. if, else if 를 활용한 계산기 만들기
// calculator 만들기
// command, a, b 인수 받기
// command는 add, subtract, multiply, divide
const calculator = function(command, a, b){
let result = 0;
if(command === 'add'){
result = a+b
return console.log(result)
}else if(command === 'subtract'){
result = a-b
return console.log(result)
}else if(command === 'multiply'){
result = a*b
return console.log(result)
}else if(command === 'divide'){
result = a/b
return console.log(result)
}else{console.log("계산할 수 없습니다.")}
}
calculator('add',10,5);
calculator('subtract',10,5);
calculator('multiply',10,5);
calculator('divide',10,5);
15
5
50
2
2. switch 를 활용한 계산기 만들기
- prompt 로 값을 받아본다.
- 그냥 a+b 로하면 string으로 인식하여 2 add 2 가 22가 되어버린다. Number()를 해주자.
- switch는 각 계산마다 break를 걸지않으면 끝까지 다 실행해버린다.
//switch 로 해보자
let command = prompt("어떻게 계산할까요?")
let a = prompt("계산할 첫번째 값을 입력해주세요")
let b = prompt("계산할 두번째 값을 입력해주세요")
switch(command){
case 'add' :
result = Number(a)+Number(b)
alert(result)
break;
case 'subtract' :
result = Number(a)-Number(b)
alert(result)
case 'multiply' :
result = Number(a)*Number(b)
alert(result)
break;
case 'divide' : alert(a/b)
default : alert("계산할 수 없습니다.")
}
728x90
'html,css,js' 카테고리의 다른 글
[CSS 기초] cascading 상속, selector 선택자, padding 패딩, margin 마진 (0) | 2023.05.17 |
---|---|
[HTML 기초] 마크업, element 요소, attribute 속성, w3c 웹표준 (0) | 2023.05.17 |
[자바스크립트 중급] Generator 제너레이터 function* (1) | 2023.05.16 |
[자바스크립트 기초] if 조건문, or and not 논리 연산자 (0) | 2023.05.16 |
[자바스크립트 중급] async, await (Promise 가독성 높히기) try & catch (0) | 2023.05.16 |