Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!