项目里,想通过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
}