.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Code Snippets >> Javascript >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Get Elements at random using Javascript

Posted By:Syed Shakeer Hussain       Posted Date: September 17, 2009    Points: 10    Category: Javascript    URL: http://www.dotnetspark.com  
 

In this example of getting JavaScript array elements randomly we have printed the array elements by the random index position of the array. For generating random numbers we have used the Math.random() function.

In our HTML code we have created an array of ten elements and have stored ten elements in this array object arrName. Now in the variables  firstRandomNumber, secondRandomNumber and thirdRandomNumber we have generated three random numbers between value "0" and "9". Each and every time when the page is refreshed it changes the value of these three random variable and therefore we get the three different elements each time in the running page. Here is the full example code for printing the array elements by the random index position: 

javascript_array_random.html

html>
  
     JavaScript array random 
    "text/javascript">
      var arrName = new Array(10);
      arrName[0"Amit";
      arrName[1"Santosh";
      arrName[2"Rose";
      arrName[3"India";
      arrName[4"News";
      arrName[5"Track";
      arrName[6"Sandeep";
      arrName[7"Suman";
      arrName[8"Saurabh";
      arrName[9"Vineet";
        var firstRandomNumber = (Math.round((Math.random()*8)+1))
      document.write("First element:="
        +arrName
[firstRandomNumber]+"
"
);
        var secondRandomNumber = (Math.round((Math.random()*8)+1))
      document.write("Second element:="
        +arrName
[secondRandomNumber]+"
"
);
        var thirdRandomNumber = (Math.round((Math.random()*8)+1))
      document.write("Third element:="
        +arrName
[thirdRandomNumber]+"
"
);
    
  
  "#ffffdd">
  
    

"blue">JavaScript array Random Examplefont>


    "submit" value="Refresh"/>
  
  


     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend