JS generates random number (specified range) of instance code _javascript tips

Source: Internet
Author: User

1, randomly generated 4-digit random number

<script language= "JavaScript" >
/**
* Randomly generated 4-bit random number
* Http://www.yulu.jb51.net
document.write (parseint (10*math.random ()));  A random integer document.write between output 0~10 (
Math.floor (Math.random () *10+1)); Output 1~10 The random integer
function rndnum (n) {
 var rnd= "";
 for (Var i=0;i<n;i++)
   Rnd+=math.floor (Math.random () *10);
 return rnd;
}
document.write (Rndnum (4)); Random integer that outputs the random number of a specified number of digits
</script>

2. Randomly generate random number of specified data range

1), starting from 1 to any value

parseint (Math.random () * Upper limit + 1);

2), starting from any value to any value

<script>
parseint (Math.random () * (upper-bound + 1) + lower bound); 
function Frandomby (under, over) { 
  switch (arguments.length) {case 
   1:return parseint (Math.random () *under+1); 
   Case 2:return parseint (Math.random () * (over-under+1) + under); 
   Default:return 0; 
  } 
} 
document.write (Frandomby (1,100)); Output random integer </script>//For random number in specified range

give the established text box a different value according to the rules [extended]
<script>
window.onload= function () { 
  var o=document.getelementsbytagname (' input '); 
  O[0].value=frandomby (1,10); 
  O[1].value=frandomby (11,20); 
  O[2].value=frandomby (1,100); 
  O[3].value=frandomby (51,100); 
}
</script>
1-10: <input type= "text"/><br/> 11-20 
: <input type= "text"/><br/> 
1-100: <input type= "text"/><br/> 51-100 
: <input type= "text"/><br/>

3, Extended examples:

 
 

This JS generation of random number (specified range) of the example code is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.