random() 方法可返回介于 0 ~ 1 之间的一个随机数。数组
这里有几种用法:dom
1.从数组中随机获取成员spa
var items = [12,a,9,p,8];
var randomItem = items[Math.floor(Math.random() * items.length)];字符串
2.生成从0到指定值的数字数组it
var numbersArray = [] , max = 100;
for( var i=1; numbersArray.push(i++) < max;); // numbers = [1,2,3 ... 100]io
3.生成随机的字母数字字符串console
function radomcharnum(len){function
var str = "";随机数
for(;str.length<len;str+=Math.random().toString(36).substr(2));方法
return str.substr(0,len);
}
3.获得指定范围的整数(须要Math.floor()或者parseInt()或者Math.ceil())
var randomNum = Math.random()*5;
console.log(parseInt(randomNum));//1
console.log(Math.floor(randomNum));//0
Math.floor(Math.random()*(max-min+1)+min);//max为期待的最大的数,min为最小的数 使用parseInt也是能够的。