用js写一个洗牌程序员。
以下是一个简单的洗牌程序:
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;
}
// Example usage:
var myArray = [1, 2, 3, 4, 5];
console.log(shuffle(myArray)); // [3, 1, 4, 5, 2]
该函数接受一个数组作为参数,并将其随机打乱。它通过使用一个while循环来遍历数组中的每个元素,并使用Math.random()函数生成一个随机索引。然后交换当前元素和随机元素的位置,直到整个数组被遍历完为止。最后,它返回打乱后的数组。
原文地址: http://www.cveoy.top/t/topic/LRP 著作权归作者所有。请勿转载和采集!