JavaScript 随机

Math.random()
Math.random() 返回 0(含)和 1(不含)之间的随机数:

示例

// 返回随机数:
Math.random();

Math.random() 始终返回小于 1 的数字。

JavaScript 随机整数

Math.random() 与 Math.floor() 一起使用可用于返回随机整数。

JavaScript 整数并不存在。

我们在这里讨论的是没有小数的数字。

示例

// 返回 0 到 9 之间的随机整数:
Math.floor(Math.random() * 10);

示例

// 返回 0 到 10 之间的随机整数:
Math.floor(Math.random() * 11);

示例

// 返回 0 到 99 之间的随机整数:
Math.floor(Math.random() * 100);

示例

// 返回 0 到 100 之间的随机整数:
Math.floor(Math.random() * 101);

示例

// 返回 1 到 10 之间的随机整数:
Math.floor(Math.random() * 10) + 1;

示例

// 返回 1 到 100 之间的随机整数:
Math.floor(Math.random() * 100) + 1;

适当的随机函数

从上面的示例中可以看出,创建一个适当的随机函数用于所有随机整数目的可能是一个好主意。

此 JavaScript 函数始终返回 min(包括)和 max(不包括)之间的随机数:

示例

function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
}

此 JavaScript 函数始终返回介于最小值和最大值(包括两者)之间的随机数:

示例

function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
}

总结

本文介绍了JavaScript Math.random()的使用,如有问题欢迎私信和评论

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐