js 区间随机数
cinob 10/27/2021 javascript
- 开箱即用版
function sectionRandom (start, end) {
let nums = end - start + 1
return Math.floor(Math.random() * nums + start)
}
sectionRandom(1, 5)
sectionRandom(2, 8)
1
2
3
4
5
6
7
2
3
4
5
6
7
- 工厂函数版
function createSectionRandomFactor (start, end) {
return () => {
let nums = end - start + 1
return Math.floor(Math.random() * nums + start)
}
}
const one2five = createSectionRandomFactor(1, 5)
one2five()
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9