JavaScript 如何生成给定范围内的随机数
通过一个无法预测结果的过程生成的数字称为随机数。在JavaScript中,可以通过使用Math.random()函数来实现。本文介绍如何使用JavaScript生成随机数。
方法1: 使用Math.random()函数
Math.random()函数用于返回一个范围在[0,1)的浮点赋值伪随机数,其中0(包括)和1(不包括)。然后可以根据所需的范围对该随机数进行缩放。
语法:
Math.random();
示例1: 此示例生成一个介于1(最小值)和5(最大值)之间的随机整数。
// Function to generate random number
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
console.log("Random Number between 1 and 5: ")
// Function call
console.log( randomNumber(1, 5) );
输出:
Random Number between 1 and 5: 1.0573617826058959
方法2:使用Math.floor()函数
Math.floor()函数 在JavaScript中用于将传入的数字参数四舍五入到最接近的整数,向下舍入即朝较小的值方向。
语法:
Math.floor(value)
示例 1: 此示例生成一个介于最小值1和最大值100之间的随机整数。
// Function to generate random number
function randomNumber(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
console.log("Random Number between 1 and 100: ")
// Function call
console.log( randomNumber(1, 100) );
输出:
Random Number between 1 and 100: 87
示例2: 这个示例生成一个介于1(最小值)和10(最大值)之间的随机整数,包括1和10。
// Function to generate random number
function randomNumber(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log("Random Number between 1 and 10: ")
// Function call
console.log( randomNumber(1, 10) );
输出:
Random Number between 1 and 10: 3
极客教程