How do I show this element otherwise than in an Alert so?

Asked

Viewed 71 times

-4

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>Mostrador JavaScript ao normal</h1>
    <script>
        let vetor = [" Script ","Java"];
        let i = 0;
        var resultado = 0;
         function Mostrar(){
            for(i=vetor.length-1;i>=0;i--){
                alert(vetor[i]+" ");
            }

         }


    </script>
    <button onclick="Mostrar()">Mostrar</button>
</body>
</html>
  • Can you see better?

  • Type need to show the vector element in an Alert only, this "Script", "Java"... want to show with an Alert so "Java Script", unused, of the function Reverse().

2 answers

0

Hello add a Alert(its vector.()); The method **reverse ()** is used for array reversal. The first element of the array becomes the last element and vice versa.

example:

<script>
let lista = ["Script","Java"];
function teste(){
    alert(lista.reverse());

}
</script>

<html>

<head>

</head>

<body>

        <button onclick="teste()" >Mostrar</button>

</body>

</html>

0

Already several ways to do this. Below I explain two of them.

Concatenation

To merge several texts into a single variable, just use concatenation (join) the texts. In Javascript you can use the function concat or the operator +.

let vetor = [" Script ", "Java"];
let i = 0;

function Mostrar() {
  let result = "";

  for (i = vetor.length - 1; i >= 0; i--) {
    result += vetor[i] + " "
  }
  
  alert(result)
}
<h1>Mostrador JavaScript ao normal</h1>
<button onclick="Mostrar()">Mostrar</button>

Arrays

How are you working with arrays, by you using the methods reverse and/or join

let vetor = [" Script ", "Java"];

function MostrarSimples() {
  /**
   * Clona o array. Isso evita que no segundo clique,
   * por exemplo, apareça "Script java"
   */
  let newArr = [...vetor]
  
  let result = newArr.reverse() // Troca a ordem dos valores (o primeiro torna-se o último etc)
    .join("") // Junta os valores. Isso evita que apareça, por exemplo "Java, Script"
  
  alert(result)
}

function MostrarComplexo() {
  /**
   * Clona o array. Isso evita que no segundo clique,
   * por exemplo, apareça "Script java"
   */
  let newArr = [...vetor]
  
  let result = newArr.reverse() // Troca a ordem dos valores (o primeiro torna-se o último etc)
    .map(value => value.trim()) // Remove os espaços em branco. Evita " Java  Script"
    .join(" ") // Junta os valores separando-os com um espaço
    
  alert(result)
}
<h1>Mostrador JavaScript ao normal</h1>
<button onclick="MostrarSimples()">Mostrar 1</button>
<button onclick="MostrarComplexo()">Mostrar 2</button>

Browser other questions tagged

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