JS数组随机排序
洗牌算法
Array.prototype.shuffle = function() {
var input = this;
for (var i = input.length-1; i >=0; i--) {
var randomIndex = Math.floor(Math.random()*(i+1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}
var tempArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
tempArray.shuffle();
console.log(tempArray);
要求不高的可以使用这个
var tempArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
tempArray = tempArray.sort(function(a, b){
return Math.random()>.5 ? -1 : 1;
});
console.log(tempArray);
来自网络
2017-05-05