Ask the user to enter 10 names and then show them reversed in Javascript

Asked

Viewed 144 times

-1

Good evening! I’m trying to resolve this issue, but I’m getting nowhere. Would you please help me?

1} Ask the user to enter 10 names. Display all the names typed on the screen, but in reverse (from last to first).

The code I’m trying to capture an HTML id and send the result there. I only got this so far:

<script>

    function invert() {

    var nome = [document.getElementById("n1").value, document.getElementById("n2").value, document.getElementById("n3").value, document.getElementById("n4").value, document.getElementById("n5").value, document.getElementById("n6").value, document.getElementById("n7").value, document.getElementById("n8").value, document.getElementById("n9").value, document.getElementById("n10").value]

    var i

    var nomes = ""

    for (i = nome.lenght-1; i >= 0; i--) {
        nomes += nome[i]
    }
    document.getElementById("here").innerHTML = nomes + ", "
    }

</script>

1 answer

0

  • No need to write the Divs one by one, just take advantage of the loop for
  • Usually the variable i is stated in the tie itself (only a good practice)
  • Use the function join to concatenate the elements of an array
function invert() {
  const names = [];

  for (let i = 10; i >= 1; i--) {
    const name = document.getElementById('n' + i).value;
    names.push(name);
  }

  const divHere = document.getElementById('here');
  divHere.innerHTML = names.join(', ');
}

Browser other questions tagged

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