#js 数租随机算法
Array.prototype.shuffle = function () {
var arr = this
for (var i = arr.length - 1; i >= 0; i--) {
var randomIdx = Math.floor(Math.random() * (i + 1))
var itemAtIdx = arr[randomIdx]
arr[randomIdx] = arr[i]
arr[i] = itemAtIdx
}
return arr
}
var tempArr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(tempArr.shuffle())//[ 5, 9, 6, 8, 4, 7, 3, 1, 2 ]
以上代码中创建了一个shuffle方法,用于随机排列数组中的元素,我们将该方法挂在到Array对象的原型下,任何数组都可以调用该方法。如:
var tempArr=[1, 2, 3, 4, 5] console.log(tempArr.shuffle())//[3, 2, 1, 4, 5]
var arr = [1,2,3,4,5,6,7,8,9,10];
arr.sort(function(){
return Math.random() - 0.5;
})
console.log(arr);
#评论
#评论 1 · 2023-02-09T08:01:04.946000Z
var arr = [1,2,3,4,5,6,7,8,9,10];
arr.sort(function(){
return Math.random() - 0.5;
})
console.log(arr);