Math中的常用方法
1.random()
语法:Math.random()
作用:获取随机数
返回值:就是0-1之间的随机数字(会出现小数),可以取到0但是取不到1
2.round()
语法:Math.round(数字)
作用:四舍五入取整
返回值:该数字四舍五入的结果
3.ceil()
语法:Math.ceil(数字)
作用:向上取整
返回值:向上取整的结果
4.floor()
语法:Math.floor(数字)
作用:向下取整
返回值:向下取整的结果
5.abs()
语法:Math.abs()
作用:求绝对值
返回值:求绝对值之后的结果
6.pow()
语法:Math.pow(x,y)
作用:求x的y次方
返回值:求完之后的结果
**也是这个作用
7.sqrt()
语法:Math.sqrt(数字)
作用:求该数字的算数平方根
8.max()
语法:Math.max(数字1,数字2,数字3.....)
作用:求一堆数字中的最大值
参数不可以写数组
9.min()
语法:Math.min(数字1,数字2,数字3.....)
作用:求一堆数字中的最小值
参数不可以写数组
10.PI
语法:Math.PI
注意:PI2个字母都是大写
可以得到近似π 的结果
随机数
// 0-1之间
var res = Math.random()
console.log(res);
// 0-10之间的(0*10=0,1*10=10)
var res1 = Math.random()*10
console.log(res1);
// 0-10之间随机整数 (0.1 9.9)
var res1 = Math.round(Math.random() * 10)
console.log(res1);
// 1-10之间的(0-10)最小取值:0 最大取值:9
// 0+1=1 9+1=10 1-10
var res1 = Math.round(Math.random() * 9) + 1
console.log(res1);
//----------------------------得出公式:Math.round(Math.random() * (max-min)) + min
// 3-7之间随机整数
// 最小取值0 最大取值4
//最小取值0+3=3
// 最大取值4+3= 7
var res = Math.round(Math.random() * 4) + 3
console.log(res);
********* 最终记住公式:Math.round(Math.random() * (max-min)) + min ***********