下列代码中的参数num为要生成数组的长度,from为起始值,to为末尾值
console.log(selectRandom(3, 0, 10))
function selectRandom (num, from, to) {
let arr = [];
let json = {};
let needNum;
if (from - to >= 0) {
console.log(111)
return '起始值要小于末尾值'
}
if (to - from == to) {
needNum = parseInt(to) + 1;
} else {
needNum = to - from;
}
if (num > needNum) {
return
} else {
while (arr.length < num) {
let ranNum = Math.ceil(Math.random() * needNum);
if (!json[ranNum]) {
json[ranNum] = 1;
arr.push(ranNum)
}
}
return arr;
}
}