Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
JS function works just sometimes

As the title says, I have a JavaScript function that doesn't always work and I don't know why.

JS:

function weapon() {
    var players = document.getElementById("playersList").value.split(",")

    var rand2
    var newPlayers = ""
    var num = players.length - 1

    for (var i = 0; i < num; i++) {
        rand2 = Math.floor(Math.random() * num)
        newPlayers += (players[rand2].trim() + ",")
        if (i != num) {
            newPlayers += "\n"
        }
        players.splice(rand2, 1)
    }

    newPlayers += players[0]
    document.getElementById("playersList").value = newPlayers
}

HTML:

<textarea id="playersList"></textarea>
<button onclick="weapon()">RANDOMIZE</button>

There's actually more code in the function but that portion works every time.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

It looks like the code can intermittently fail at this line:

  newPlayers += (players[rand2].trim() + ",")

At the end of your for loop, you call:

  players.splice(rand2, 1)

where splice mutates the state of players, and reduces the amount of items in the array by 1.

When the next iteration of the loop is called, rand2 has the possibility of generating a value that is greater than the amount of items in the players array. You will then receive an error if you try to access an index position which doesn't exist.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda