Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 获取随机数

作者:角落里哭泣   发布日期:2026-05-03   浏览:112

// 获取随机数的几种方法

// 1. 获取0到1之间的随机小数(不包括1)
let randomDecimal = Math.random();
console.log(randomDecimal); // 输出一个0到1之间的随机小数

// 2. 获取指定范围内的随机整数
function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

console.log(getRandomInt(1, 10)); // 输出1到10之间的随机整数,包括1和10

// 3. 获取指定范围内的随机浮点数
function getRandomFloat(min, max) {
    return Math.random() * (max - min) + min;
}

console.log(getRandomFloat(1.5, 5.5)); // 输出1.5到5.5之间的随机浮点数

解释说明:

  • Math.random():返回一个0到1之间的随机小数(不包括1)。
  • getRandomInt(min, max):通过Math.random()生成0到1之间的随机小数,然后乘以范围差值,并加上最小值,最后用Math.floor()取整,从而得到指定范围内的随机整数。
  • getRandomFloat(min, max):类似地,通过Math.random()生成随机小数,但不进行取整操作,从而得到指定范围内的随机浮点数。

上一篇:js 获取时区

下一篇:js forin

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站