how to store objects in an array?

2

I have the following code and I do not really know how to do so that each player is saved in a list of players, that is, in array

For example, if I want to iterate over their own objects, I have to assign an ID to each player? It occurs to me that their id could be their index in array , but if so, < strong> how do I assign ID, if I have not saved the player in an array yet?

function Jugador(name, edad, dinero) {

  this.name = name;
  this.edad = edad;
  this.dinero = dinero;

}

function obtenerNombre() { // Obtengo el nombre del input

  var obtenerN = document.getElementById("nombre").value;
  return obtenerN;

}

function obtenerEdad() { // Obtengo la edad del input

  var obtenerE = document.getElementById("edad").value;
  obtenerE = parseInt(obtenerE);

  return obtenerE;
}

function crearJugador() {

  var jug = new Jugador(obtenerNombre(), obtenerEdad(), 0);
  document.write(jug.name, jug.edad, jug.dinero);
}
<!DOCTYPE html>
<html>

<head>
  <title>HTML5, CSS3 and JavaScript demo</title>
</head>

<body>
  <!-- Start your code here -->

  <style>
    body {
      background-color: #111111;
    }
    
    h1 {
      color: white;
    }
  </style>
  <form>
    <input type="text" id="nombre" placeHolder="Nombre" />
    <input type="text" id="edad" placeholder="edad" />
    <input type="button" onClick="obtenerNombre(); obtenerEdad(); crearJugador();" value="Enviar mis datos!" />

  </form>



  <!-- End your code here -->
</body>

</html>
    
asked by Eduardo Sebastian 08.05.2017 в 20:41
source

3 answers

2

Here is an example of creating an array of players and calculating the id of the new player based on the elements already existing in the array.

After creating the new player I call a function to list all the players in the array to show how you can traverse it.

EDIT. I edit the example to show how I could modify (add money) to a particular player using his id.

function Jugador(id, name, edad, dinero) {
  this.id = id;
  this.name = name;
  this.edad = edad;
  this.dinero = dinero;   
}

var jugadores = [];

function obtenerNombre() {  // Obtengo el nombre del input
  
  var obtenerN = document.getElementById("nombre").value;
  return obtenerN;
  
}
function obtenerEdad() { // Obtengo la edad del input
  
  var obtenerE = document.getElementById("edad").value;
  obtenerE = parseInt(obtenerE);
  
  return obtenerE;
}

function crearJugador() {
  
  var jug = new Jugador(jugadores.length + 1, obtenerNombre(), obtenerEdad(), 0);
  jugadores.push(jug);
  mostrarListado();
}

function mostrarListado(){
  var lista='';
  for(var i=0; i<jugadores.length; i++){
    lista+= 'id: ' + jugadores[i].id +
      ' nombre: ' + jugadores[i].name + 
      ' edad: ' + jugadores[i].edad + 
      ' dinero: ' + jugadores[i].dinero + '\n';
  }
  document.getElementById('listado').innerText = lista;
}

function sumarDinero(){
  var dinero = parseInt(document.getElementById('dinero').value);
  var id = parseInt(document.getElementById('jugadorid').value);
  if (!(isNaN(dinero) || isNaN(id))){
    for (var i=0; i<jugadores.length; i++){
      if (jugadores[i].id==id){
        jugadores[i].dinero+= dinero;
      }
    }
    mostrarListado();
  }
  
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<!-- Start your code here -->

  <style>
    body {
      
      background-color: #111111;
    }
   h1, div {
      
      color: white;
  }
   
    
  </style>
  <form>
    <input type="text" id="nombre" placeHolder="Nombre"/>
    <input type="text" id="edad" placeholder="edad"/>
    <input type="button" onClick="crearJugador();" value="Enviar mis datos!"/>
        
  </form>
  
  <form>
    <input type="number" id="jugadorid" placeHolder="id" />
    <input type="number" id="dinero" placeHolder="dinero" />
    <input type="button" onClick="sumarDinero();" value="Sumar dinero" />
  </form>
  
  <div id="listado"></div>

<!-- End your code here -->
</body>
</html>
    
answered by 08.05.2017 / 20:59
source
1

You can do the following, shortening your code, you only need one class and two functions (one of which is optional and is only to show a visual result):

// Declaramos un arreglo donde guardar nuestros jugadores
var misJugadores = []; 

// Obtenemos nuestro elemento donde mostrar los jugadores
var jugadores = document.getElementById('jugadores');

// Creamos una clase llamada jugador con un constructor que reciba 3 párametros
class Jugador {

  constructor(nombre, edad, dinero) {
    this.nombre = nombre;
    this.edad = edad;
    this.dinero = dinero;
  }

}

// Función para crear nuestro jugador
function crearJugador() {
  // Obtenemos el nombre dado por el usuario
  var nombre = document.getElementById('nombre').value;
  // Obtenemos la edad dad por el usuario y la parseamos
  var edad = parseInt(document.getElementById('edad').value)
  // Creamos nuestro jugador
  var jugador = new Jugador(nombre, edad, 0);
  // Lo añadimos a nuestro arreglo
  misJugadores.push(jugador);
  // Actualizamos nuestra tabla
  actualizarJugadores();
}

// Con esta función recorremos a todos nuestros jugadores
// en el arreglo anteriormente creado
// y los mostramos en la tabla
function actualizarJugadores() {
  // Limipamos la tabla para no repetir jugadores
  jugadores.innerHTML = ''; 
  // Recorremos nuestros jugadores
  for (var i = 0; i < misJugadores.length; i++) {
    // Añadimos nuestros jugadores a la tabla
    jugadores.innerHTML = jugadores.innerHTML +
          '<tr>' +
              '<td>' + misJugadores[i].nombre + '</td>' +
              '<td>' + misJugadores[i].edad + '</td>' +
              '<td>' + misJugadores[i].dinero + '</td>' +
          '</tr>';
  }
}
* {
  font-family: Arial;
  text-align: center;
}

table {
  width: 100%;
}
<form>
  <input type="text" id="nombre" placeHolder="Nombre" />
  <input type="text" id="edad" placeholder="Edad" />
  <input type="button" onClick="crearJugador();" value="Enviar mis datos!" />
</form>
<hr />
<h1>Mis Jugadores</h1>
<button onclick="actualizarJugadores();">Actualizar jugadores</button><br /><br />
<table border="1" cellspacing="0">
  <tr>
    <td>Nombre</td>
    <td>Edad</td>
    <td>Dinero</td>
  </tr>
  <tbody id="jugadores"></tbody>
</table>
    
answered by 08.05.2017 в 21:08
0

In the following example we create an array of 1 single element, the element has an index 0 and value 'Name one':

var ejemplo = ["Nombre uno"];

In the following example we create an associative array (object) of 2 elements; one with index A13 and value 'Name one' and another with index 10 and value 'Name two':

var ejemplo = {A13:"Nombre uno", 10:"Nombre dos"};

Then we can use the arrays with a for or similar:

for (var key in ejemplo) {
  if (p.hasOwnProperty(key)) {
    console.log(key + " -> " + p[key]);
  }
}

or direct:

console.log(ejemplo);

Edit: Written for JS

    
answered by 08.05.2017 в 21:11