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); }
}
}
When you remove the found element, you are passing in a string literal instead of the variable name:
Since there is no element
'randomAllGroundShoes', the element would never be found, and no elements would ever be removed from the array.It should be:
But, you are doing the same thing more than once. You don’t need to check
allGroundShoes.indexOf()at all. You could just store the random number in a variable and reference it again. But, even that is more than you need. Just callsplice()to get your value:This way, you retrieve your value and remove it from the array in one step – no additional lookup required.
jsfiddle.net/kRNTg