简体   繁体   中英

How to create a simple calculator using switch case and function using Javascript

I'm new to Javascript and just finished learning switches and conditionals and I wanted to create my calculator where it first asks the user what they want to do and gets the two digits from them and goes ahead and alerts them with an answer. But every time I try to run the function it gives me an undefined error enter code here

let tell = prompt("What would you  like to do (*,/,+,-)");
let dig1 = prompt("Enter first Number");
let dig2 = prompt("Enter second Number")

function calculate(a,b) {
    let answer = tell;
    switch (a,b) {
        case "*":
            answer = a * b;
            break;
        case "/":
            answer = a / b;
            break;
        case "+":
            answer = a + b;
            break;
        case "-":
            answer = a - b;
            break
    }
}

alert(calculate(dig1,dig2))

 let tell = prompt("What would you like to do (*,/,+,-)"); let dig1 = prompt("Enter first Number"); let dig2 = prompt("Enter second Number") function calculate(a,b) { // check the value of the `tell` is one of these cases and return the result. switch (tell) { case "*": return a * b; case "/": return a / b; case "+": return a + b; case "-": return a - b; default: return "You didn't a correct opertor" } } alert(calculate(+dig1, +dig2))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM