第一种方法:Fisher-Yates算法实现
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
// Used like so
var arr = [2, 11, 37, 42];
arr = shuffle(arr);
console.log(arr);
运行结果:
[
2,
42,
11,
37
]
第二种方法:
var arr = [4,1,67,12,45,121,3];
arr.sort(function() {
return (0.5-Math.random());
})
代码分析:
arr.sort(function(){ return 0.5 - Math.random() })
sort 是对数组进行排序 ,他的是这样工作的。每次从数组里面挑选两个数 进行运算。
- 如果传入的参数是0 两个数位置不变。
- 如果参数小于0 就交换位置
- 如果参数大于0就不交换位置
接下来用刚才的较大数字跟下一个进行比较。这样循环进行排序。 恰好。我们利用了这一点使用了0.5 - Math.random 这个运算的结果要么是大于0,要么是小于0.这样要么交换位置,要么不交换位置。当然大于或者小于0是随即出现的。所以数组就被随即排序了。
第三种方法:
/**
* Returns a new array whose contents are a copy shuffled of the array.
* @param {Array} a items to shuffle.
* https://stackoverflow.com/a/2450976/1673761
*/
const shuffle = (array) => {
let currentIndex = array.length;
let temporaryValue;
let randomIndex;
const newArray = array.slice();
// While there remain elements to shuffle...
while (currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = newArray[currentIndex];
newArray[currentIndex] = newArray[randomIndex];
newArray[randomIndex] = temporaryValue;
}
return newArray;
}; 继续阅读与本文标签相同的文章
上一篇 :
拨开区块链的云雾,攻破三元悖论的不可能
-
健乐教学机器人可开展的教学实训内容
2026-05-14栏目: 教程
-
5G套餐曝光遭“吐槽”,iphone11受追捧,导致苹果11销量比较高
2026-05-14栏目: 教程
-
为什么修电脑的叫自己不要杀毒和清理垃圾?
2026-05-14栏目: 教程
-
当水乡建筑遇上机器人,成就乌镇又一网红景点
2026-05-14栏目: 教程
-
惊险!手刹失灵,郴州一货车开启“无人驾驶”模式……
2026-05-14栏目: 教程
