基本概念
Math和其他的对象不同,它不是一个构造函数,它属于一个工具类不用创建对象,它里边封装了数学运算相关的属性和方法。
文档:
https://www.w3cschool.cn/jsref/jsref-obj-math.html
Math属性
Math方法
- 代码演示
console.log(Math.PI);
console.log(Math.abs(-20));
// 向上取整
console.log(Math.ceil(1.1));
// 向下取整
console.log(Math.floor(1.1));
// 四舍五入
console.log(Math.round(1.5));
// 生成(0-1)之间的随机数,左右都是开区间
console.log(Math.random());
// 生成 0 -10 之间的随机数
console.log(Math.round(Math.random()*10));
// 生成 1 -10 之间的随机数
console.log(Math.round(Math.random()*9+1));
输出:
Math.random()的用法
Math.random()
直接使用,可以用来生成一个0-1之间的随机数- 生成一个
0-10
的随机数:
Math.round(Math.random()*10);
- 生成一个0-x之间的随机数
Math.round(Math.random( )*×);
- 生成一个1-10:
Math.round(Math.random()*9+1);
- 生成一个
x-y
之间的随机数
Math.round (Math.random( )*(y-x)+x);