js数组乱序
2017-07-26 本文已影响0人
任无名F
- 使用Array的sort方法
Array.prototype.shuffle = function() {
this.sort((a,b) => {
return Math.random() * 2 - 1; // 随机返回1或-1
});
}
- 更高效的方法,时间复杂度为n
Array.prototype.shuffle = function() {
for(let t, j, i = this.length; i;) {
j = Math.floor(Math.random() * i); // 在前i项中随机取一项,与第i项交换
t = this[--i];
this[i] = this[j];
this[j] = t;
}
}