随机数
Math.random()
即Math
对象的random()
方法,会返回一个0~1的随机数(包括0但不包括1)。Math.floor()
即Math
对象的floor()
方法,对一个数进行下舍入。
如果需要生成一个 1~n 之间的随机数(包括1包括n)代码如下:1
2
3function randomNum(n) {
return Math.floor(Math.random() * n) + 1;
}
Math.random() * n
返回一个 0~n 的随机浮点数(包括0但不包括n)。Math.floor(Math.random() * n)
返回一个 0~(n-1) 的随机整数(包括0包括(n-1))。Math.floor(Math.random() * n) + 1;
返回一个 1~n 的随机整数数(包括1包括n)。
洗牌算法
1 | function randomArray(length) { |
- 生成两个空数组arr1与arr2。
- 用for循环构建arr1为一个正常排序数组。
- 生成一个小于数组长度的随机数。
- 将arr1“随机数”位置的数抽出添加到arr2中。
- 将arr1最后一个位置的数抽出放到“随机数”位置。
- 循环直至arr1中所有数都被抽完,输出随机数组arr2。
随机颜色
两种方法的区别在于颜色的不同表达方式。1
2
3
4
5
6
7
8
9
10function randomColor1() {
var r = Math.floor(Math.random() * 256);
var g = Math.floor(Math.random() * 256);
var b = Math.floor(Math.random() * 256);
return "rgb(" + r + "," + g + "," + b + ")";
}
function randomColor2() {
return "#" + Math.floor(Math.random() * 0xffffff).toString(16);
}