方法一

// 生成 1 ~ 10 随机数
Math.floor(Math.random() * 10 + 1);

// 数组乱序
var arr = [1,2,3,4,5,6,7,8,9];
var newArr = [];
for(var i = 0; i<arr.length; i++) {
    var index = Math.floor(Math.random() * arr.length); // 随机下标
    newArr.push(arr[index]); // 将随机元素放至新数组
    arr.splice(index,1);    // 原数组删除随机元素
}
arr = [...arr, ...newArr];

讲解一下,上面代码的难点是 这一段 Math.floor(Math.random() * arr.length),

Math.random() 生成的是 大于等于0,小于1的随机数, 所以该随机数乘于几最多只能无限接近那个数,因为随机数小于1,

eg: Math.random()*5 大于等于0,小于5(最多无穷接近5)。

Math.floor 刚好可以向下取整。

 

上面的随机排序的方法只对一半数字随机,后面的是合上去的。

改进版,

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var newArr = [];
var len = arr.length;
for (var i = 0; i < len; i++) {
    var index = Math.floor(Math.random() * arr.length); //随机下标
    newArr.push(arr[index]); //将随机出的元素,存放新数组newArr中去
    arr.splice(index, 1); //    将随机出的元素在arr中删除
}
console.log(newArr)

这里直接写死数组的长度

 

方法二

使用 数组 sort 的方法进行乱序

[1,2,3].sort((a,b) => Math.random() > 0.5 ? -1 : 1)

 

posted on 2021-03-15 11:53  京鸿一瞥  阅读(225)  评论(0)    收藏  举报