本文共 654 字,大约阅读时间需要 2 分钟。
如何获取一个随机不重复数组
方法1
const randomNum = () => Math.floor(Math.random() * 10);const count = 30;const uniqueList = [];for (let index = 0; index < count; index++) { const num = randomNum(); if(!uniqueList.includes(num)){ uniqueList.push(num) }}// 耗时:0.415283203125 ms// 第一次 (9) [7, 3, 8, 5, 9, 0, 1, 6, 2]// 第二次 (10) [9, 6, 7, 1, 3, 5, 0, 2, 8, 4]// 可见30次的遍历循环也不一定能每次生成10以内的10个随机不重复数据,这种方案下唯一能做的就是增加循环的次数,但是这种方法导致执行时间很长。不推荐
方法2
const count = 10;const list = [];for (let index = 0; index < count; index++) { list.push(index + 1);}list.sort(function () { return 0.5 - Math.random() * 1});// 耗时0.39306640625 ms// 推荐这种方法// 提前生成10个样本池然后再打散排序。
转载地址:http://ydejn.baihongyu.com/