随机数、洗牌算法与随机颜色

随机数

Math.random()Math对象的random()方法,会返回一个0~1的随机数(包括0但不包括1)。
Math.floor()Math对象的floor()方法,对一个数进行下舍入。
如果需要生成一个 1~n 之间的随机数(包括1包括n)代码如下:

1
2
3
function 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
2
3
4
5
6
7
8
9
10
11
12
13
14
function randomArray(length) {
var arr1 = [],
arr2 = [],
i, randomNum;
for (i = 0; i < length; i++) {
arr1[i] = i + 1;
}
for (i = length; i > 0;) {
randomNum = Math.floor(Math.random() * i);
arr2.push(arr1[randomNum]);
arr1[randomNum] = arr1[--i];
}
return arr2;
}
  1. 生成两个空数组arr1与arr2。
  2. 用for循环构建arr1为一个正常排序数组。
  3. 生成一个小于数组长度的随机数。
  4. 将arr1“随机数”位置的数抽出添加到arr2中。
  5. 将arr1最后一个位置的数抽出放到“随机数”位置。
  6. 循环直至arr1中所有数都被抽完,输出随机数组arr2。

随机颜色

两种方法的区别在于颜色的不同表达方式。

1
2
3
4
5
6
7
8
9
10
function 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);
}