JS——Math常用的方法

425 阅读1分钟

1. Math.floor 向下取整

image.png

2. Math.ceil 向上取整

image.png

3. Math.round 四舍五入

image.png

4. Math.abs 绝对值

image.png

5. Math.max 最大值

image.png

6. Math.min 最小值

image.png

7. Math.random 随机数 0~1 包括0 不包括1

image.png

8. 返回随机整数 利用Math.random, Math.floor

(1)Math.floor(Math.random() * 10) // 返回 0 ~ 9之间的整数

(2)Math.floor(Math.random() * 11) // 返回 0 ~ 10之间的整数

(3)Math.floor(Math.random() * 100) // 返回 0 ~ 99之间的整数

(4)Math.floor(Math.random() * 101) // 返回 0 ~ 100之间的整

(5)Math.floor(Math.random() * 10) + 1 // 返回 0 ~ 10之间的整数

(6)Math.floor(Math.random() * 100) + 1 // 返回 0 ~ 100之间的整数

可以总结成 Math.floor(Math.random() * (max - min)) + min // min ~ max之间的整数 包括min 不包括max Math.floor(Math.random() * (max - min + 1)) + min //min ~ max 既包括min 又包括max