Receive the numeric keys to make some functions equal for all of them on the switch in a calculator

Asked

Viewed 32 times

1

  switch (e.target.value) {
        case "A/C":
            console.log('ae')
            break;
        case "C":
            break;
        case "X":
            break;
        case ".":
            break;
        case "%":
            break;
        case "-":
            break;
        case "√":
            break;
        case "+":
            break;
        case "÷":
            break;
        case "=":
            break;
        **case IsNumber():
            console.log('é um numero')
            break;**
    }

I am developing a calculator in JS. I would like to receive the numeric keys to make some functions equal for all of them. Is it possible to recognize if the key clicked.value is a number on the switch? Or I will have to do key by key, or maybe a statemente, etc?

1 answer

3


The purpose of using a switch instead of if/Else is that the switch creates a hashtable and finds the result by association. Even if it was possible to declare a function on the switch, there would be no way to find the match by association, so it would be no different than an if/Else.

In other words, yes, you will have to use an if, or else put all the options inside the switch.

switch (e.target.value) {
    case "A/C":
        console.log('ae')
        break;
    case "C":
        break;
    case "X":
        break;
    case ".":
        break;
    case "%":
        break;
    case "-":
        break;
    case "√":
        break;
    case "+":
        break;
    case "÷":
        break;
    case "=":
        break;
    default:
        if (!isNaN(e.target.value)) {
            console.log('é um numero')
        }
}

Or:

switch (e.target.value) {
    case "A/C":
        console.log('ae')
        break;
    case "C":
        break;
    case "X":
        break;
    case ".":
        break;
    case "%":
        break;
    case "-":
        break;
    case "√":
        break;
    case "+":
        break;
    case "÷":
        break;
    case "=":
        break;
    case "1": case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "0":
        console.log('é um numero')
        break;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.