Math 是一个内置对象,它拥有一些数学常数属性和数学函数方法。Math 不是一个函数对象。
Math 用于 Number 类型。它不支持 BigInt。
与其他全局对象不同的是,Math 不是一个构造器。Math 的所有属性与方法都是静态的。
ceil()
Math.ceil() 函数返回大于一个数的最小整数,即一个数向上取整后的值。
//生成一个1-10的随机数
Math.ceil(Math.random()*10);
//Math.random()*10会得到0-10但不包括10的随机数,然后通过Math.ceil向上取整得到0-9的随机整数
floor()
既然有向上取整,那么当然会有向下取整。
Math.floor()返回小于一个数的最大整数,即一个数向下取整后的值。
Math.floor(0.8)==>0
Math.floor(1.1)==>1
round()
Math.round()
返回四舍五入后的整数。
Math.round(0.8)==>1
Math.round(1.1)==>1
random()
这应该是Math对象中使用场景最多的一个方法了。
产生一个0-1之间不包括一的随机数。一般情况下,我们使用Math.random()的时候,会搭配parseint或Math.ceil()或Math.floor或Math.round()来使用。
生产一个0-9的随机整数:
Math.floor(Math.random()*10);
//Math.random()*10会得到0-10但不包括10的随机数,然后通过Math.floor向下取整得到0-9的随机整数
parseint(Math.random()*10);
//Math.random()*10会得到0-10但不包括10的随机数,然后通过parseint强制转换为整数得到0-9的随机整数
这里就要说说Math.floor和parseint之间的区别了
Math.floor()是下取整,将一切都转为数字,再取整
parseInt()取整,将一切都转为字符串,再按位读数字字符
参数是数字的时候,两者无差别:
Math.floor(123.456)=>parseInt(123.456)=>123
参数是包含非数字的字符串:
parseInt("12.5px")=>12
Math.floor("12.5px")=>Math.floor(Number("12.5px"))=>Math.floor(NaN)=>NaN
参数是bool类型:
Math.floor(true)=>1
Math.floor(Number(true))=>1
parseInt(true)=>NaN
parseInt(String(true))=>parseInt("true")=>NaN
下面来说一些随机数常用的场景
JS实现使用Math.random()函数生成n到m间的随机数字
生成n-m,包含n但不包含m的整数:
第一步算出 m-n的值,假设等于w
第二步Math.random()w
第三步Math.random()w+n
第四步parseInt(Math.random()*w+n, 10)
生成n-m,不包含n但包含m的整数:
第一步算出 m-n的值,假设等于w
第二步Math.random()w
第三步Math.random()w+n
第四步Math.floor(Math.random()*w+n) + 1
生成n-m,不包含n和m的整数:
第一步算出 m-n-2的值,假设等于w
第二步Math.random()w
第三步Math.random()w+n +1
第四步Math.round(Math.random()w+n+1)
或者 Math.ceil(Math.random()w+n+1)
生成n-m,包含n和m的随机数:
第一步算出 m-n的值,假设等于w
第二步Math.random()w
第三步Math.random()w+n
第四步Math.round(Math.random()w+n) 或者 Math.ceil(Math.random()w+n)
举个栗子:
生成100-1000的随机整数
// n = 100; m = 1000
// m - n = 1000 - 100 = 900
// Math.random()*900
// Math.random()*900 + 100
var num = Math.round(Math.random()*900 + 100);