---
title: "javascript 实现随机数"
author: "txf2004"
date: "2008-12-12T09:33:00Z"
tags: []
slug: "javascript"
draft: false
lastmod: "2009-09-19T08:14:21Z"
id: 471347
url: "https://txf2004.iteye.com/blog/471347"
---

Math对象中的方法  
Math.random() 该方法返回一个0到1之间的随机数，不包括0和1。  
要实现获得一个maxNumber到minNumber范围内的随机整数，实现方法如下：  
choNumber=maxNumber-minNumber+1;  
number=Math.floor(Math.random()\*choNumber+minNumber)

例：  
选择一个1到10之间的随机数：  
number=Math.floor(Math.random()\*10+1);  
可能出现的值有10个，最小的值为1。  
选择一个2到10之间的随机数：  
number=Math.floor(Math.random()\*9+2);  
可能出现的值有9个，最小的值为2。  
解释：Math.floor()用来获取一个整数，将小数转换成整数。

通过函数实现从一个数组中随机选择一个值：  
实现selectFrom()函数获得一个iFirstValue到iLastValue之间的随机整数  
function selectFrom(iFirstValue,iLastValue)  
{  
var iChoices=iLastValue-iFirstValue+1;  
return Math.floor(Math.random()\*iChoices+iFirstValue);  
}

例：

var aColors=\["red","green","yellow","black","blue","purple","brown"];  
var sColors=aColors\[selectFrom(0,aColors.length-1)]