js 区间随机数

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
  • 工厂函数版
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
Last Updated: 9/22/2023, 6:04:11 AM