JavaScript 数学 (Math) 方法

一、Math 方法

1、Math.round(x) 的返回值是 x 四舍五入为最接近的整数:

Math.round(7.8);    // 返回 8
Math.round(3.3);    // 返回 3

 

2、Math.random() 返回介于 0(包括) 与 1(不包括) 之间的随机数:

Math.random()    //返回随机整数

 

3、Math.pow(x, y) 的返回值是 x 的 y 次幂:

Math.pow(4, 2);      // 返回 16

 

4、Math.sqrt(x) 返回 x 的平方根:

Math.sqrt(64);      // 返回 8

 

5、Math.ceil(x) 的返回值是 x 上舍入最接近的整数:

Math.ceil(6.4);     // 返回 7

 

6、Math.floor(x) 的返回值是 x 下舍入最接近的整数:

Math.floor(2.7);    // 返回 2

 

7、Math.abs(x) 返回 x 的绝对(正)值:

Math.abs(-4.7);     // 返回 4.7

 

8、Math.min() 和 Math.max() 可用于查找参数列表中的最低或最高值:

Math.min(0, 450, 35, 10, -8, -300, -78);  // 返回 -300

Math.max(0, 450, 35, 10, -8, -300, -78);  // 返回 450

 

 

二、JavaScript 随机整数

Math.random() 与 Math.floor() 一起使用用于返回随机整数。

Math.floor(Math.random() * 10);		// 返回 0 至 9 之间的数

Math.floor(Math.random() * 11);		// 返回 0 至 10 之间的数

Math.floor(Math.random() * 10) + 1;	// 返回 1 至 10 之间的数

 

posted @ 2022-04-18 12:20  CodeFan*  阅读(357)  评论(0编辑  收藏  举报