项目里,想通过js来生成一个范围内的随机整数,php使用惯了,有函数提供。
查看js,使用 Math.random。而只能随机0-1之间。
如何实现任意范围的数呢?
function randomIntFromInterval(min,max)
{
return Math.floor(Math.random()*(max-min+1)+min);
}
更好的是参考,火狐开发者文档:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math/random
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}
本文介绍了一种在JavaScript中生成指定范围内随机整数的方法,并提供了详细的函数实现代码。此外,还给出了Mozilla开发者文档中关于Math.random函数的参考资料。
691

被折叠的 条评论
为什么被折叠?



