String change for arithmetic operator

Asked

Viewed 57 times

0

Is there any way to make the code below more dynamic, like when choosing the switch desired he already do the multiplication table?

var num = parseFloat(prompt('Digite um numero'))
var sinalTabuada = prompt('Digite o sinal que desejar descobrir a tabuada')
var indice = 1;

 switch(sinalTabuada){
    case '+':
        while(indice <= 10){
            document.write('a soma de ' + num + sinalTabuada + indice + ' = ' + (num 'sinalTabuada' indice) + '<br>'); // transformar o sinalTabuada em operador aritimetico mesmo..
        indice++;
        }
    break;
  • 2

    Maybe the eval be what you are looking for. I just recommend that before reading that and that

  • Another tip - not directly related - is to give more meaningful names to variables. sinalTabuada implies multiplication, but if the signal can receive any operation, maybe the variable name should be sinal, operacao, sinalOperacao, or something like that. The same for the message, which says "The sum of...", but in fact it will not always be the sum. They may seem like silly details, but better names and better messages help when programming and understand what is doing/happening.

  • Thanks for the help and tips!

1 answer

2

As @hkotsubo commented, you can use eval to solve your problem. I made an example to help you:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Tabuada</title>
  </head>
  <body>
    <script type="text/javascript">
      const numero = parseFloat(prompt("Digite um numero"));
      const sinal = prompt("Digite o sinal que desejar descobrir a tabuada");
      let valor = 1;

      if (sinal === "+" || sinal === "-" || sinal === "/" || sinal === "*") {
        while (valor <= 10) {
          document.write(
            `A soma de ${numero} ${sinal} ${valor} = ${eval(
              numero + sinal + valor
            )} <br/>`
          );
          valor++;
        }
      } else {
        console.error("Sinal inválido.");
      }
    </script>
  </body>
</html>

I hope I’ve helped! '-'

  • 1

    It helped a lot, opened my mind! Thank you!

Browser other questions tagged

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