【JavaScript】Math 对象

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)xy 次方
  • 如果参数不是 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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JS.Huang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值