Math 对象
Math 对象是 JS 的内置对象,可以直接使用
console.log(typeof Math, Math); // object Math {abs: ƒ, acos: ƒ, …}
常用属性 Math.PI
:圆周率 3.141592653589793
常用方法
1. Math.random()
:[0, 1)
之间的随机数
获取 [x, y)
之间的数值:
Math.random() * (y-x) + x
2. Math.min(a,b)
:获取最小参数值
- 如果参数不是 number,会隐式转换,转不了也就比不来,返回
NaN
- 可以传入 0 ~ n 个参数,不传参返回
Infinity
Math.min(1, 2, 3, 4) // 1
如果要获取数组中的最小值,可以使用 apply
函数 / 扩展运算符 ...
:
Math.min.apply(null, [5, 2, 6, 4, 9]) // 2
Math.min(...[5, 2, 6, 4, 9]) // 2
3. Math.max(a,b)
:获取最大参数值
- 不传参返回
-Infinity
- 其他参考
min()
4. Math.ceil(x)
:向上取整
- 如果参数不是 number,会隐式转换,转不了,则返回
NaN
- 不传参返回
NaN
Math.ceil(1.1) // 2
Math.ceil(-1.1) // -1
5. Math.floor(x)
:向下取整
- 如果参数不是 number,会隐式转换,转不了,则返回
NaN
- 不传参返回
NaN
Math.floor(1.1) // 1
Math.floor(-1.1) // -2
获取 [x, y]
之间的随机整数:
Math.floor(Math.random() * (y - x + 1)) + x
6. Math.round(x)
:四舍五入
- 如果参数不是 number,会隐式转换,转不了,则返回
NaN
- 不传参返回
NaN
- 负数的四舍五入的绝对值 == 负数的绝对值四舍五入
Math.round(1.1) // 1
Math.round(-1.1) // -1
7. Math.abs(x)
:取绝对值
- 如果参数不是 number,会隐式转换,转不了,则返回
NaN
- 不传参返回
NaN
Math.abs(1.1) // 1.1
Math.abs(-1.1) // 1.1
8. Math.sin(x)
:正弦值
Math.sin(Math.PI/6)
9. Math.cos(x)
:余弦值
10. Math.tan(x)
:正切值
11. Math.pow(x, y)
:x
的 y
次方
- 如果参数不是 number,会隐式转换,转不了,则返回
NaN
- 传 0 / 1 个参数,返回
NaN
-
x
y
支持负数
Math.pow(2, -2) // 0.25
12. Math.sqrt(x)
:x
的平方根
- 如果参数不是 number,会隐式转换,转不了,则返回
NaN
- 不传参返回
NaN
Math.sqrt(4) // 2
四位随机验证码
function unique() {
let str = "0123456789abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWSYZ";
let newStr = "";
for (let i = 0; i < 4; i++) { // 可重复的验证码
newStr += str[Math.floor(Math.random() * str.length)];
}
return newStr;
}
console.log(unique());
function unique() {
let str = "0123456789abcdefghijklmnopqrstuvwsyzABCDEFGHIJKLMNOPQRSTUVWSYZ";
let newStr = "";
for (let i = 0; i < 4; i++) {
let random = Math.floor(Math.random() * str.length);
if (newStr.indexOf(str[random]) !== -1) { // 不重复的验证码
i--;
continue;
} else {
newStr += str[random];
}
}
return newStr;
}
console.log(unique());
保留 n 位小数:num.toFixed(n)
会以 string 形式四舍五入成 n 位小数
Math.sin(Math.PI/6).toFixed(2); // 0.50