JavaScript之Math对象

Math对象

Math对象中封装很多与数学相关的属性和方法。

Math对象没有构造函数Math(),无需创建它,通过把 Math 作为对象使用可以直接调用其所有属性和方法。

  • 圆周率
// 圆周率  π  Math.PI
console.log( Math.PI );//3.141592653589793
  • 最大值/最小值(重要)
//最大值:Math.max()
//最小值:Math.min()
console.log(Math.max(1, 2, 3, 4, 5, 6, 7));//7
console.log(Math.min(1, 2, 3, 4, 5, 6, 7));//1
// 如果想传一个数组可以用apply方法  
console.log(Math.max.apply(null, [1, 2, 3, 4, 5, 6, 7]));//7
console.log(Math.min.apply(null, [1, 2, 3, 4, 5, 6, 7]));//1

戳这里详细了解apply方法

  • 随机数(重要)
 //随机数: Math.random()  得到一个随机数——》 0~0.9999999999999999 
 //可以取到0,不能取到1——》[0,1)

// 求0~n中所有随机整数
parseInt( Math.random() * (n + 1) )

// 求随机的rgb的颜色
// rgb(0,0,0)——》每一项的取值范围 0~255
var r = parseInt( Math.random() * 256 );
var g = parseInt( Math.random() * 256 );
var b = parseInt( Math.random() * 256 );

var color = 'rgb(' + r + ',' + g + ',' + b + ')';
  • 取整
// 1、Math.ceil() 向上取整  取大的那一个
console.log( Math.ceil(1.1) );// 2
console.log( Math.ceil(1.9) );// 2
console.log( Math.ceil(-1.1) );// -1
console.log( Math.ceil(-1.9) );// -1

// 2、Math.floor() 向下取整 取小的那一个
console.log( Math.floor(1.1) );// 1
console.log( Math.floor(1.9) );// 1
console.log( Math.floor(-1.1) );// -2
console.log( Math.floor(-1.9) );// -2

// 3、Math.round()  四舍五入
console.log( Math.round(1.1) );// 1
console.log( Math.round(1.9) );// 2
console.log( Math.round(-1.1) );// -1
console.log( Math.round(-1.9) );// -2
  • 绝对值
// 绝对值  Math.abs()
console.log( Math.abs(10) );//10
console.log( Math.abs(-10) );//10
  • 次幂(次方)
// 次方  Math.pow(n,m) n的m次方
console.log( Math.pow(2,2) );// 2的2次方  4
console.log( Math.pow(3,2) );// 3的2次方  9
  • 开方
// 开方  Math.sqrt()
console.log( Math.sqrt(100) ); //10
console.log( Math.sqrt(9) );  //3
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值