Reputation: 7
first sorry my english. Im making a little program to sort football players into two teams, A and B. 6 players, 3 for A and 3 for B. With a random number generator of course.
In Java i have no problem, i made this program and runs perfect, but i dont know much about JS and array item removings seems a little diferent here.
My code:
function hola(){
var primero = document.getElementById("1").value;
var segundo = document.getElementById("2").value;
var tercero = document.getElementById("3").value;
var cuarto = document.getElementById("4").value;
var quinto = document.getElementById("5").value;
var sexto = document.getElementById("6").value;
var jugadores = [primero,segundo,tercero,cuarto,quinto,sexto];
var eq1=[];
var eq2=[];
while (jugadores.length > 0){
var largoArray = jugadores.length;
var rand = Math.round(Math.random()* largoArray);
console.log("before the if, array jugadores haves ",jugadores.toString() ," and his size is ",jugadores.length);
if (eq1.length < 3){
eq1.push(jugadores[rand]);
remove(jugadores,jugadores[rand]);
}else {
eq2.push(jugadores[rand]);
remove(jugadores,jugadores[rand]);
}
}
document.getElementById("resultado").innerHTML= eq1 + " y el equipo B: " + eq2;
console.log("equipo 1 ", eq1);
console.log("equipo 2", eq2);
}
function remove(array, element) {
const index = array.indexOf(element);
if (index !== -1) {
array.splice(index, 1);
}
}
and it return to me:
"equipo 1 (3) [undefined, "iniesta", "ronaldo"] script2.js:35 equipo 2 (4) ["messi", "ronaldinho", "maradona", "pele"]"
also the console logs i made to depurate seems to work fine... The array is 1 element shorter each cicle, and array.lenght match the desired sizes.
What am doing wrong?
Upvotes: 0
Views: 53
Reputation: 245
Arrays (like Java) start with the index 0.
The range of random numbers you are generating varies from 0 to 6 (array has only 6 elements).
var rand = Math.round(Math.random()* largoArray);
Instead use,
var rand = Math.round((Math.random()* largoArray)-1);
Upvotes: 0
Reputation: 32176
The problem is on the line:
Math.round(Math.random() * largoArray)
Since that will sometimes return an index that is beyond the bounds of the array. When that happens, this code:
eq1.push(jugadores[rand]);
remove(jugadores,jugadores[rand]);
Won't work, since jugadores[rand]
is undefined
, so you end up pushing undefined
into one of your arrays, without removing anything from the original jugadores
array.
To fix this, use the Math.floor
function instead, changing the line to:
Math.floor(Math.random() * largoArray)
Upvotes: 1