javascript, use the prompt to collect data

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 enter variables instead of leaving them predefined.

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

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

    
asked by anonymous 07.07.2018 / 06:48

1 answer

1

Since promprt , like alert , blocks execution of the code 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 this with less code, but it may be 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);
    
07.07.2018 / 10:01