javascript, use of prompt to gather data

Asked

Viewed 100 times

2

<script type="text/javascript">

        /* calcular a media de 4 notas */


        var n1 = 10
        var n2 = 10
        var n3 = 10
        var n4 = 10

        var media = (n1+n2+n3+n4)/4

        document.write("Sua média:", media);

</script>

Next, I wanted to use the Prompt mdn to type variables, instead of leaving them preset.

I also wanted to create a function to type some predefined texts, instead of using document.write() all the time.

I’m a beginner, if you can help me, thank you!

1 answer

1


Since the promprt, like the alert, blocks code execution you can do it like this:

const nrDeNotas = 4; // talvez no futuro isto também seja um prompt('Quantas notas?');

const notas = Array(nrDeNotas)
  .fill()
  .map((_, i) => prompt('Insira a nota nr ' + (i + 1)))
  .map(Number);

const media = notas.reduce((soma, nota) => soma + nota, 0) / nrDeNotas;
document.write('A média é de ' + media + ' valores');

You can do it with less code but it might get harder to read:

const media = ['', '', '', ''].reduce((soma, nota, i, arr) => soma + Number(prompt('Insira uma nota')) / arr.length, 0);
document.write('A média é ' + media);

  • My, very good! I would never imagine doing something like this, very fucking! I was impressed my... I didn’t know what const was, but I’m doing the homework here.

  • I think it’s incredible that you answer in a way that I never imagined.

  • Thank you very much, I will study about const!

  • @Mshijo I’m glad I helped. If the answer solved your problem you can mark as accepted. And if you want you can use var but read about it: https://answall.com/a/206121/129

  • 1

    Never use! haha I laughed kk...

  • 1

    and I used a lot in the code... Thank you so much for helping!

Show 1 more comment

Browser other questions tagged

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