Log In · Register

 
make it random.
OneOfTheseDayz
post Feb 13 2006, 11:14 AM
Post #1


Ill get around to doing that....
*****

Group: Member
Posts: 518
Joined: Oct 2005
Member No: 275,913



Does anyone know how to make a javascript random??????
 
 
Start new topic
Replies
*mipadi*
post Feb 13 2006, 04:42 PM
Post #2





Guest






Okay. The first thing to do is populate the array, which is best done like this:
CODE
var mem=[];

mem[0]=["Anime feak","http://s15.invisionfree.com/Animeupgrade/index.php?showuser=15"];
mem[1]=["Lottery","http://s15.invisionfree.com/Animeupgrade/index.php?showuser=18"];
mem[2]=["Raze","http://s15.invisionfree.com/Animeupgrade/index.php?showuser=26"];

This gives you a two-dimensional array with the values you desire.

Now, you want to generate two or three users to display. This is a bit tough. I'd first generate a random number of entries using Math.random():
CODE
var displayNumUsers = Math.floor(Math.random() * 3);
if (displayNumUsers < 2)
{
   count++;
}

That will give you a counter that will hold either the value 2 or 3.

Now, just loop through and display the users. First, create a variable to hold the number of users displayed, then a variable to hold the users that have been displayed.
CODE
var count = 0;
var users=[];
users[0] = -1;
users[1] = -1;
users[2] = -1;
while (count <= displayNumUsers)
{
   var user;
   var index;
   index = Math.floor(Math.random() * mem.length);
   while (index == users[0] || index == users[1] || index == users[2])
   {
       index = Math.floor(Math.random() * mem.length);
   }
   user = mem[index];
   //code for displaying user, using variable user
   count++;
   users[count - 1] = index;
}

Admittedly, this I hacked this code out pretty quick, so it's not optimized. I'm not an expert in JavaScript and I haven't tested this code, but I'm fairly confident it will work, or it can be fixed easily.
 

Posts in this topic


Closed TopicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members: