JavaScript Math 数学对象-数据类型

最大最小值

1Math.max(1, 3, 4, 5, 9) // 最大值
2Math.min(1, 3, 4, 5, 9) // 最小值
3Math.max.apply(Math, [2, 3, 6]) // 最大值
4Math.min.apply(Math, [2, 3, 6]) // 最小值

舍入

1Math.ceil(1.3) // 向上舍入
2Math.floor(1.9) // 向下舍入
3Math.round(1.49) // 1 四舍五入(只看小数点后一位数)
4Math.floor(Math.random() * 10 + 1)
5// 随机一个 [A - B] 之间的随机数
6function selectFrom(A, B) {
7  return Math.floor(Math.random() * (B - A + 1) + A)
8}
9selectFrom(2, 9) // 生成 2-9(包括 2 和 9)的随机数

其他方法

1var num = -2.4;
2Math.abs(num);// 绝对值
3Math.exp(num);// 返回 Math.E 的 num 次幂
4Math.log(num);// 自然对数
5Math.pow(num,p);// num 的 p次幂
6Math.sqrt(num);// num的平方根
7Math.PI();// 表示数学中的 π 代表的是 180 的弧度
81弧度 = Math.PI() / 1809----下面的方法传入的值要是弧度,不能传数字----
10Math.acos(x);// x 的反余弦值
11Math.asin(x);// x 的反正弦值
12Math.atan(x);// 反正切值
13Math.atan2(x,y)// y/x 的反正切值
14Math.cos(x)// x 的余弦值
15Math.sin(x)// x 的正弦值
16Math.tan(x)// x 的正切值
17-------------------------
18Math.cbrt(1); // 1  计算一个数的立方根
19Math.cbrt('1'); // 1 会对非数值进行转换
20Math.imul(1, 2);  // 2 大多数情况下,与 a*b 相同

ES6 扩展方法

1// Math.trunc 方法用于去除一个数的小数部分,返回整数部分。
2// 隐式调用 Number 方法
3Math.trunc(4.1) // 4
4Math.trunc(-4.9) // -4
5Math.trunc('123.456') // 123
6Math.trunc(false) // 0
7Math.trunc(null) // 0
8// Math.sign 方法用来判断一个数到底是正数、负数、还是零。
9/* 参数为正数,返回 +1;
10 * 参数为负数,返回 -1;
11 * 参数为 0,返回 0;
12 * 参数为 -0,返回 -0;
13 * 其他值,返回 NaN。
14 */
15Math.sign(5) // +1
16Math.sign(0) // +0
17Math.sign(-0) // -0
18Math.sign(Number.NaN) // NaN