赞
踩
利用Math对象中的random函数
进行一个随机点名的应用
Math.random();//返回一个随机的小数x 0<=x<1 //可以查阅MDN文档 其中内容很详细 console.log(Math.random());//获得随机数 //应用:得到两个数之间的随机整数 并且 包含这两个整数 function getRandom(min,max){ return Math.floor(Math.random()*(max-min+1))+min;//固定的算法 } //检验 console.log(getRandom(1,10)); //1到10之内的随机整数(包括自己)被输出了~ //应用:随机点名 var arr = ['张三','李四','王二麻子']; console.log(arr[getRandom(0,arr.length-1)]);
这其中需要注意的是 生成两个数之间的随机整数的算法:
function getRandom(min,max){
return Math.floor(Math.random()*(max-min+1))+min;
//固定的算法
}
使用此算法 getRandom函数可以返回在【min,max】范围内的任意一个随机数
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。