I am writing a script that onload will add a class to a random 4 of 12 DIV's and then remove the ID of the DIV from the array.
I have an array setup with all 12 DIV ID's in it.
Sometimes when I reload the page, 4 DIV'S have that class and other times only 3 DIV's have that class.
Kinda stuck on why this is happening. I commented out the remove from array code to see if that was the issue, but still same problem.
Here is my code:
//Randomize Which Shoes Are Positive And Negative
function randomizeShoes(){
allGroundShoes = new Array('ground_black_1','ground_black_2','ground_brown_1','ground_brown_2','ground_clown_1','ground_clown_2','ground_disco_1','ground_disco_2','ground_moccasins_1','ground_moccasins_2','ground_red_1','ground_red_2');
for(var i=0; i < 4; i++){
randomAllGroundShoes = allGroundShoes[Math.floor(Math.random() * allGroundShoes.length)];
$('#'+randomAllGroundShoes+'').addClass('shoeNegitive');
//randomShoeID = allGroundShoes.indexOf('randomAllGroundShoes');
//if(randomShoeID != -1){ allGroundShoes.splice(randomShoeID, 1); }
}
}
Math.floor(Math.random() * allGroundShoes.length)
needs to beMath.floor(Math.random() * allGroundShoes.length - 1)
because arrays start at 0. The length will return 12 butallGroundShoes[12]
will not exist, as the last item would beallGroundShoes[11]
since it starts atallGroundShoes[0]
. – MrXenotype Nov 21 '12 at 0:06Math.random()
returns a floating point number from 0.0 to less than 1 (i.e. 0 inclusive to 1 exclusive). See the MDN page for details. – GregL Nov 21 '12 at 0:11