原理及步骤
1.定义一个数组(shuffled),长度(length)是原数组(arr)长度
2.取 0 到 index (初始0) 随机值 rand, shuffled[index] = shuffled[rand], shuffled[rand] = arr[index]
3.index++ ; 重复第二步,直到 index = length -1
简单来说,就是 shuffled 从 0 到 length-1 的赋值过程,并且新加入的值是 arr[index]。
代码实现
1.代码一
function random(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
function shuffle(arr) {
var length = arr.length, shuffled = Array(length);
for (var index = 0, rand; index < length; index++) {
rand = random(0, index);
if (rand !== index) shuffled[index] = shuffled[rand];
shuffled[rand] = arr[index];
}
return shuffled;
}
测试用例:
var arr = ['dfewfew', 2, 3, 4, 5, 6, 7, "fdf'", { kdofkod, jiji, miojim }];
shuffle(arr);
console输出:
[3, "dfewfew", 7, 2, 4, Array(3), "fdf'", 5, 6]
其中, Array(3):length:3
0:"kdofkod"
1:"jiji"
2:"miojim"
2.代码二
function shuffle(arr) {
var i, j, temp;
for (i = arr.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
};
测试用例:
var arr = ['dfewfew', 2, 3, 4, 5, 6, 7, "fdf'", { kdofkod, jiji, miojim }];
shuffle(arr);
console输出:
[7, 3, "dfewfew", "fdf'", Array(3), 4, 6, 2, 5]
其中, Array(3):length:3
0:"kdofkod"
1:"jiji"
2:"miojim"
参考资料
Fisher–Yates shuffle 洗牌算法
JavaScript学习笔记:数组随机排序
洗牌算法:给数组随机排序
洗牌算法Fisher_Yates原理