Vue3项目,用ts写一个方法,生成1到50的随机整数,包含1和50
在Vue3项目中结合TypeScript生成1到50随机整数(含边界值)的方法如下:
<script setup lang="ts">
const generateRandomInt = (): number => {// 生成[min, max]范围内的随机整数const min = 1const max = 50return Math.floor(Math.random() * (max - min + 1)) + min
}
</script>
实现说明:
Math.random()
生成[0,1)
的浮点数- 乘以
(max - min + 1)
得到[0,50)
范围 Math.floor()
向下取整得到[0,49]
整数- 加最小值1后得到
[1,50]
的闭区间结果
验证边界值:
- 当
Math.random()
返回0时: 0 × 50 + 1 = 1 0 \times 50 + 1 = 1 0×50+1=1 - 当
Math.random()
接近1时: 0.999999 × 50 ≈ 49.999 0.999999 \times 50 ≈ 49.999 0.999999×50≈49.999 →Math.floor
得49 → 49 + 1 = 50 49 + 1 = 50 49+1=50
使用方法:
<template><button @click="generateRandomInt">生成随机数</button><div>当前值:{{ generateRandomInt() }}</div>
</template>