基础知识
Math.abs() //取绝对值 不四舍五入
Math.floor(); //向下取整。
Math.ceil(); //向上取整。
Math.round(); //四舍五入取整。
Math.random(); //返回 0(含)和 1(不含)之间的随机数 [0,1)
parseInt(); //第一个参数对以数字开头的字符串或数字都能向下取整,第二个参数默认为10进制
parseInt与Math.floor区别
Math.floor只能对一个数向下取整,不能解析字符串
Math.floor(1.5) // 1
Math.floor(-2.1) // -3
Math.floor("3") // 3
Math.floor('Hello') // NaN
Math.floor('16岁') // NaN
parseInt(string, radix)可将任意数字开头字符串转换为相应整数,后一个参数表进制,可取值2/8/10/16,默认是十进制
parseInt(1.5) // 1
parseInt(1.2) // 1
parseInt(-2.1) // -2
parseInt('3') // 3
parseInt('hello') // NaN
parseInot('16岁') // 16
1.生成[0,max)的随机数:
parseInt(Math.random() * max);
Math.floor(Math.random() * max);
2.生成[0,max]的随机数:
// max - 最大值
parseInt(Math.random() * (max + 1));
Math.floor(Math.random() * (max + 1));
因为Math.random()生成[0,1)的数,所以1是取不到的。那么如果想最大值取到1,就需要最大值加1,但是加完1后最大值多了点,所以还需要parseInt或Math.floor向下取整。
3.生成[1,max]的随机数:
// max - 最大值
parseInt(Math.random() * max) + 1;
Math.floor(Math.random() * max) + 1;
4.生成[min,max]的随机数:
// max - 最大值
// min - 最小值
parseInt(Math.random() * (max - min + 1) + min);
Math.floor(Math.random() * (max - min + 1) + min);
运用
随机生成一个字符串
function hash () {
let s = ''
const strs = [
'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z', '0', '1',
'2', '3', '4', '5', '6', '7', '8',
'9',
]
for(let i = 0; i < 10; i++) {
s += strs[Math.floor(Math.random() * strs.length)]
}
return s
}
hash()
简化版
//36代表36进制
const str = Math.random().toString(36).substr(2,10)
console.log(str)
更多推荐
js随机数生成
发布评论