如何重新随机化或者重新排序JavaScript的数组元素?例如数组:
var arr1 = ["a", "b", "c", "d"];
如何随机化或者重新排序这个数组的元素?
重新随机化或者重排数组的算法实现和使用示例如下:
// 数组随机化或重排算法
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;
}
// 使用方法
var arr = [1, 9, 8, 7, 6];
arr = shuffle(arr);
console.log(arr);
评论前必须登录!
注册