js中的phprand函式

wensongyu發表於2015-12-29
//檔案rand.js
function MyRand(min, max){
	this.min = min;
	this.max = max;
}

MyRand.prototype.getRand = function(){
		//parseInt(this.max * random()) 取整,此值肯定小於給的最大值
	var temp = parseInt(this.max * Math.random());
	while(temp < this.min){
		 temp = parseInt(this.max * Math.random());
	}
	return temp;
};

//檔案index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>index</title>
		<meta name="author" content="Administrator" />
		<script type="text/javascript" src="rand.js"></script>
		<!-- Date: 2015-12-29 -->
		<script type="text/javascript">
			var rand = new MyRand(20, 30);
			var res = rand.getRand();
			alert(res);
			rand = null;//及時釋放類存
		</script>
	</head>
	<body>

	</body>
</html>

 


相關文章