Ask for names with a prompt and store them in an array in javascript

2

You are supposed to ask for 3 names with prompt, use an array to store and then display their values.

function names() {
    var nombres = [];
    var cont;
    for (int i = 0; i <= 2; i++) {
        var x = prompt("Ingresa tu nombre:", "");
        nombre[i] = x;
    }
    for (int i = 0; i <= 2; i++) {
        cont += nombres[i] + " ";
    }
    document.getElementById("here").innerHTML = cont;
}
    
asked by Victor Manuel Orozco Covarrubi 02.11.2016 в 14:52
source

3 answers

2

There were a couple of mistakes but if you're learning it's normal. Notice that I used push to add the new elements to the end of the array and that I have initialized x before entering the for since it will be used several times and it is not correct to initialize it in each round

Here is a possible version, I hope you find it useful:

function names() {
    var nombres = [];
    var cont = '';
    var x;

    for (i = 0; i <= 2; i++) {
        x = prompt("Ingresa tu nombre:", "");
        nombres.push(x);
    }

    for (i = 0; i <= 2; i++) {
        cont += nombres[i] + " ";
    }

    document.getElementById("here").innerHTML = cont;
}
    
answered by 02.11.2016 / 15:22
source
4
  • In the loops for , where it says int you must use var : In javascript the variables are not typed and there is no type int , the numbers use Number but this is automatic .

  • When you capture the names the name of the array is wrong: it says nombre but the variable is called nombres (plural)

  • the variable cont must be initialized because then you use the operator += . Otherwise it would be "undefined" at the beginning of the chain.

  • Salu2

    function names() {
        var nombres = [];
        var cont = "";
        for (var i = 0; i <= 2; i++) {
            var x = prompt("Ingresa tu nombre:");
            nombres[i] = x;
        }
        for (var i = 0; i <= 2; i++) {
            cont += nombres[i] + " ";
        }
        document.getElementById("here").innerHTML = cont;
    }
    
    names();
    <div id="here"></div>
        
    answered by 02.11.2016 в 15:16
    0

    You can also avoid some lines, you can do it in the following way:

    function names() {
      var nombresList = [];
      for (var i = 0; i <= 2; i++) {
        var nombre = prompt("Ingresa tu nombre:");
        nombresList.push( nombre ); 
      }
      /* Con Join podemos unir los item de la lista */
      document.getElementById("here").innerHTML = nombresList.join(" ");
    }
    
    names(); // Iniciar la función
    <div id="here"></div>

    With nombresList.join(" ") we can join the items in the list, if we put a hyphen instead of placing a space between the quotes they would link the items with hyphens ... nombre-nombre-nombre

        
    answered by 24.10.2018 в 16:52