Home > Web Front-end > JS Tutorial > body text

js生成随机数的方法实例_javascript技巧

WBOY
Release: 2016-05-16 15:36:27
Original
2108 people have browsed it

js生成随机数主要用到了内置的Math对象的random()方法。用法如:Math.random()。它返回的是一个 0 ~ 1 之间的随机数。有了这么一个方法,那生成任意随机数就好理解了。比如实际中我们可能会有如下的需要:
(1)生成一个 0 - 100 之间的随机整数,那么则可以:

parseInt(100*Math.random()); 
Copy after login

注意:因为Math.random()的返回值是包括0和1的,所以这里是有生成0和100的可能性的。
(2)生成一个从 m - n 之间的随机整数,例如要生成一个 5 - 15 之间的随机数,则可以:

parseInt(Math.random()*(15-5+1) + 5); 
Copy after login

概括即为:

parseInt(Math.random()*(n-m+1)+m);//生成一个从 m - n 之间的随机整数
Copy after login

另外根据需要总结了另外两种常用到的方法,如下:
(3)生成指定位数的随机整数

function randomNum(n){ 
 var t=''; 
 for(var i=0;i<n;i++){ 
 t+=Math.floor(Math.random()*10); 
 } 
 return t; 
} 
Copy after login

(4)生成指定范围内的随机整数

function randomNum(minNum,maxNum){ 
 switch(arguments.length){ 
 case 1: 
  return parseInt(Math.random()*minNum+1); 
 break; 
 case 2: 
  return parseInt(Math.random()*(maxNum-minNum+1)+minNum); 
 break; 
 default: 
  return 0; 
 break; 
 } 
} 
Copy after login

例如生成 2 - 9之间的随机整数,则:randomNum(2,9),生成 1 - 22之间随机整数,则:randomNum(22)

以上就是汇总的js生成随机数的方法,希望对大家的学习有所帮助。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!