快速的让一个数组乱序
方法1:使用数组的sort方法结合随机数
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
arr.sort(function() {
return Math.random() - 0.5;
});
console.log(arr);
方法2:使用Fisher-Yates算法
function shuffleArray(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(shuffleArray(arr));
方法3:使用lodash库的shuffle方法
import shuffle from 'lodash/shuffle'
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(shuffle(arr));
对比总结:
- 方法1使用数组的
sort
方法结合随机数,是一种简单快速的方式,但并不是真正意义上的乱序,因为它是通过排序来实现的。 - 方法2使用
Fisher-Yates
算法,通过交换数组中的元素来实现乱序,是一种更可靠的乱序方式。 - 方法3使用
lodash
库的shuffle
方法,提供了一个方便的工具函数来实现数组的乱序,不需要自己编写乱序算法。
总体而言,如果只是需要简单的乱序,方法一已经足够。但如果对于乱序的质量和随机性有较高的要求,可以使用方法二的Fisher- Yates算法或者借助第三方库来实现。
THE END
暂无评论内容