Math方法是JavaScript提供的方法,可以直接使用
Math.random():随机数
随机生成一个生成a - b范围的数值,a小b大
公式parseInt(Math.random()* (b+1-a) + a );
例如要生成20 - 80范围的随机数,代码就是parseInt(Math.random()* (61) + 20 );
可以应用于定义随机颜色
function setColor(){
var c1 = parseInt(Math.random()*256);
var c2 = parseInt(Math.random()*256);
var c3 = parseInt(Math.random()*256);
// 将随机颜色定义为rgb字符串作为返回值
return `rgb(${c1},${c2},${c3})`;
}
Math.round():四舍五入取整
var float1 = 123.156;
console.log( Math.round(float1) );//结果为123
Math.ceil()和Math.floor():向上取整和向下取整,整数部分进一和只保留整数部分
var float1 = 123.156;
console.log( Math.ceil(float1) );//整数部分进一,结果为124
console.log( Math.floor(float1) );//只保留整数部分,结果为123
Math.pow():乘方运算,有两个参数,第一个是底数,第二个是指数
console.log(Math.pow(2,5)); // 计算2的5次方
// Math.sqrt() 求平方根
console.log(Math.sqrt(9)); // 9的平方根,是3
// Math.abs() 求绝对值
console.log(Math.abs(-9)); // -9的绝对值,是9