JS生成一个6位数的随机数常用的集中方法
在JavaScript中生成一个6位数的随机数,主要利用Math.random()随机函数,以及结合数字和字符串转化、截取的方法来实现
Math.random() //生成随机数
Math.round() //四舍五入
Math.ceil() //向上取整
Math.floor() //向下取整
Math.abs() //取绝对值
Math.sin(x) //x的正弦值,返回值在 -1.0 到 1.0 之间
Math.cos(x) //x的余弦值,返回的是 -1.0 到 1.0 之间的数
parseInt() //转整数
parseFloat() //转浮点数
toString() //转字符串
slice() //字符串截取
1. 方法一
function getMathRandom() {
let result = ''
for(var i=0;i<6;i++){
result += Math.floor(Math.random()*10);
}
return result
}
2. 方法二
function getMathRandom() {
let chars = '0123456789'
let result = ''
for (let i = 0; i < 6; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length))
}
return result
}
3. 方法三
function getMathRandom() {
let result = parseInt(Math.random()*1000000)+1000000
return result.toString().slice(0, 6)
}
如果想在生成的随机数前面添加或者拼接当前时间,还可以参考以下文章:
js获取当前时间并且拼接6位数的随机数