举例:
[1,2,3,4,5,6,7,8] 长度为8
结果:乱序输出且不重复且长度不变
例如输出:[5,8,2,4,1,5,7,3]
方案一、
function shuffle(array) {
var j, x, i;
for (i = array.length; i; i--) {
j = Math.floor(Math.random() * i);
x = array[i - 1];
array[i - 1] = array[j];
array[j] = x;
}
return array;
}
console.log(shuffle([1,3,4,5,7,8,9,78]))
方案二、
let aa= [1,2,3,4,5,6,7,8].sort(() => {
return Math.random()> 0.5 ? -1 :1;
// 上面这行如果返回true则表示两个元素交换位置,为false则表示两个元素不交换位置
})
// console.log(aa)
方案三、
let bb= [1,2,3,4,5,6,7,8].sort(() => {
return Math.random() -0.5
})
console.log(bb)
参考链接:https://blog.csdn.net/a17634399794/article/details/82457779?utm_medium=distribute.pc_aggpage_search_result.none-task-blog-2~aggregatepage~first_rank_ecpm_v1~rank_v31_ecpm-6-82457779-null-null.pc_agg_new_rank&utm_term=sort%20%E4%B9%B1%E5%BA%8F&spm=1000.2123.3001.4430