1.Math
一些常用的数学方法,包括随机数,绝对值等等。
(1)Math.PI
PI = 3.141592653589793
(2)Math.round(num)
四舍五入取整数
Math.round(1.2); 1
Math.round(1.5); 2
(3)Math.pow(n, e)
第一个参数是基数,第二个参数是指数
Math.pow(2,3); // 8
(4)Math.sqrt(num)
开平方根
Math.sqrt(36); // 6
(5)Math.abs(num)
取绝对值
Math.abs(-1.2); // 1.2
(6)Math.ceil(num) 和 Math.floor(num)
一个是向上取整,一个是向下取整
Math.ceil(1.2); // 2
Math.floor(1.2); // 1
(7)Math.sin()和Math.cos();
Math.sin(90 * Math.PI / 180); // 1
Math.cos(0 * Math.PI / 180); // 1
(8)Math.min(arr)和Math.max(arr)
Math.min(0, 2, 4, 1); // 0
Math.max(0, 2, 4, 1); // 4
(9)Math.random()
返回的是0-1之间的小数
Math.random();
2.随机数
Math.floor(Math.random()*10); // 0-9之间的随机数
Math.floor(Math.random()*11); // 0-10之间的随机数
Math.floor(Math.random()*10 + 1); // 1-10之间的随机数
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min) ) + min;
} // [min,max)
function getRndInteger(min, max) {
return Math.floor(Math.random() * (max - min + 1) ) + min;
} // [min,max]