JavaScript 内置对象之-Math

       Math是 JavaScript 的原生对象,提供各种数学功能。该对象不是构造函数,不能生成实例,所有的属性和方法都必须在Math对象上调用。
       Math对象的属性,提供以下一些数学常数:
1 Math.E:常数e。

2.Math.PI:常数 Pi(π)。

var r = 80;
var s = Math.PI*r*r;
document.write("半径为80的圆面积是:"+s);   // 20106.193

3.Math.abs:返回参数值的绝对值。

Math.abs(1);			 // 1
Math.abs(-1); 			 // 1

4.Math.max:返回参数之中最大的那个值;
5.Math.min:返回最小的那个值。

注意: (如果参数为空, Math.min返回Infinity, Math.max返回-Infinity,Infinity 用于存放表示正无穷大的数值。)

Math.max(6,8,2); 	// 8
Math.min(6,9,-5); 	// -5
Math.min(); 		// Infinity 
Math.max(); 		// -Infinity

6.Math.floor:小于参数值的最大整数(地板值)。

Math.floor(3.9);  // 3
Math.floor(-3.2); // -4

7.Math.ceil:返回大于参数值的最小整数(天花板值)。

Math.ceil(3.1);  // 4
Math.ceil(-3.1); // -3

8.Math.round:用于四舍五入(取最近值)。

Math.round(0.1); 	// 0
Math.round(0.5);  	// 1
Math.round(0.6); 	// 1
Math.round(-1.1); 	// -1
Math.round(-1.5); 	// -1
Math.round(-1.6);	// -2

9.Math.pow:返回以第一个参数为底数、第二个参数为幂的指数值。

// 等同于 2 * 2
Math.pow(2, 2) // 4
// 等同于 2 *2* 2
Math.pow(2, 3) // 8

10.Math.sqrt:返回参数值的平方根。

如果参数是一个负值,则返回NaN;

Math.sqrt(4)  // 2
Math.sqrt(-4) // NaN

11.Math.sin():返回参数的正弦(参数为弧度值);
     Math.cos():返回参数的余弦(参数为弧度值);
     Math.tan():返回参数的正切(参数为弧度值);

例: 30*Math.PI/180 →30度转为弧度.

Math.sin(0); 			// 0
Math.cos(0); 			// 1
Math.tan(0); 			// 0
Math.sin(Math.PI / 2);   // 1

12.Math.random():返回0到1之间的一个伪随机数,可能等于0,但是一定小于1。

Math.random(); // 0.43467364134782

注:任意范围的随机整数生成函数如下。

function getRandomInt(min, max) {
return parseInt(Math.random() * (max - min + 1)) + min;
// return Math.round(Math.random()*(max - min)+min);
}
getRandomInt(1, 6); // 5

实例:
①首先封装一个随机数函数:

function random(min, max) {
  return Math.round(Math.random()*(max - min)+min);
}
random(min, max) ;

②使用:

// 生成一个rgb的随机颜色值,结果使用字符串显示:例:rgb(210,145,67);
function randomRgb(){
	return "rgb(" + random (0,255) + "," + random (0,255) + "," + random (0,255) + ")";
}
发布了18 篇原创文章 · 获赞 57 · 访问量 1765

猜你喜欢

转载自blog.csdn.net/weixin_42881768/article/details/104459623