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.
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.