思路
- 生成一个两数之间的整数,使用到Math的random函数
 
random
random()会返回一个浮点型伪随机数字,范围[0, 1)
- 返回一个两数之间的 随机数 ,范围在[start, end)
 
Math.random()*(end - start)
- 返回一个两数之间的 整数 ,范围在[start, end)
 
// floor向下取整
Math.floor(Math.random()*(end - start))
- 返回一个两数之间的 整数 ,范围在[start, end]
 
Math.floor(Math.random()*(end - start+1)) + start
此题中要求的是第三种情况
代码
 			const _getUniqueNums = (start,end,n) => {
                // 补全代码
                const res = []
                while(res.length < n) {
                  let num = Math.floor(Math.random()*(end-start+1))+start
                  // 不能有重复的元素
                  if (!res.includes(num)) {
                    res.push(num)
                  }
                }
                return res
            }

京公网安备 11010502036488号