题目
给定一个数组,及一个长度n,生成长度为n的不重复随机数组,n不大于数组中不重复元素个数
方法一
const getRandomArr = function (arr, n) {
const...result = [];
while (result.length n) {
// 生成随机数
const randomNum = arr[Math.floor(Math.random...3, 1]
getRandomArr([1,2,3,4,5,6,7], 4); // [1, 3, 5, 6]
getRandomArr([1,2,3,4,5,6,7], 2); // [7, 4]
复制代码...;
const map = new Map();
while (result.length n) {
// 生成随机数
const randomNum = arr[Math.floor...{
map.set(randomNum, randomNum);
result.push(randomNum);
}
}
return result;
};
复制代码