知识点
- 程序健壮性
- 各种思路
题目
编写一个JavaScript函数uniqueNums
,该函数有一个参数n
(一个不大31
的整数),其返回值是一个数组,该数组内是n
个随机且不重复的整数,且整数取值范围是[2, 32]
。
实现
首先对传入的参数要进行一定的约束和判断。
const uniqueNums = (n) => {
// 非数字退出
if (typeof n !== 'number') {
return [];
}
// 非整数退出
if (~~n !== n) {
return [];
}
if (n > 31 || n < 1) {
return [];
}
const min = 2, max = 32;
let result = [];
// 主体部分
return result;
};
console.log(uniqueNums(5))
然后主题部分的思路,一开始想到的是通过结果数组的长度作为循环判断条件,循环添加一个范围内的随机数
可以使用while
:
let result = [];
while (result.length < n) {
const random = Math.round(Math.random()