Math对象
1.Math.PI //圆周率
Math.PI
2.Math.random //生成随机数
例子 1、取两个数之间的随机整数
function getRandom(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
例子 2、随机生成RGB颜色 如 rgb(100,123,45) 取值范围 [0,255] 随机生成颜色
function getRandom(min, max) { //取两个数中的随机数
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
function getRgb(min,max){
var color1 = getRandom(min,max);
var color2 = getRandom(min,max);
var color3 = getRandom(min,max);
return 'rgb(' + color1 + ',' + color2 + ',' + color3 + ')';
}
console.log(getRgb(0,255)); //传递一个范围
3.Math.floor //向下取整/Math.ceil //向上取整
Math.floor( 45.95); //向下取整
Math.ceil( 45.95); //向上取整
4.Math.round //取整四舍五入
Math.round(2.5);// 3
5.Math.abs // 绝对值
Math.abs('-1'); // 1
6.Math.max //最大值 /Math.min 最小值
Math.max(3,8,5); //最大值
Math.min (9,7,3); //最小值
例子求数组中的最大值
var arr = [3,9,6];
var max = Math.max(...arr);
console.log(max);
7.Math.pow //求指数
Math.pow(2,3); //2的3次方
8.Math.sqrt //返回一个数的平方根
Math.sqrt(9); // 3
9、Math.log //函数返回一个数的自然对数
Math.log(1); // 0