例如:生成一个长度为10,且不重复,数组的每一项在20-40之间
function getRandom(start, end) {
const choices = end - start + 1;
return Math.floor(Math.random() * choices + start);
}
function getUnique(len, start, end) {
let arr = [],
random;
while(len > 0) {
random = getRandom(start, end);
if (arr.indexOf(random) === -1) {
arr.push(random);
len--;
}
}
return arr;
}
console.log(getUnique(10, 20, 40)); // [36,26,40,23,38,35,39,28,34,32]