I'm using regular JavaScript.
As the headline suggests I'm getting a RangeError and I don't really know how to avoid it. The real problem is that I should not get it, and indeed if I refresh the page there's a one out of ten chance (estimated) that the error isn't thrown.
THE CODE: (its about picking random objects from an array)
I have a an array like this:
var array = ["item1", "item2", "item3", "item4"]
and so on, actually I have like 5 arrays, containing together around 4000 characters. I use a function to generate a random number:
function getRandomNumber(start, range) {
range = range + 1;
return Math.floor( (Math.random() * (range - start) ) + start );
}
This function works and I even refined my initial approach with help from the web to look like as it is now.
So I call this function like this:
function getObjects() {
var randomObject1 = array[getRandomNumber(1, array.length -1)]
var randomObject2 = array[getRandomNumber(1, array.length -1)]
var randomObject3 = array[getRandomNumber(1, array.length -1)]
var drawnItems = [randomObject1, randomObject2, randomObject3]
if(drawnItems.length != new Set(drawnItems).size) {
getObjects()
}
}
I need multiple objects drawn each round, so I do this multiple times as shown. I do end up with an array that contains the random items drawn like above.
Then I use this code to determine if the drawn items can be stored in a Set, which is not important, but a convenient way of checking if there are any objects that were drawn twice. => I can only have each object once in the final output.
I can see how this all can be problematic, but I don't really understand why the computer faces the problem but I don't, if I refresh like a few times. What I'm saying is that in fact the computer will try more often than I have to refresh to hit a valid constellation. Why does the PC face the problem even though he's trying even more often?
This first happened when I tried drawing 3 objects out of an array containing only 4. If I draw from my large 100+ objects array I never face problems.
Aucun commentaire:
Enregistrer un commentaire