Math数学对象

Math数学对象

本章单词

math 数学
PI 圆周率
max 最大
min 最小
floor 地板(去掉小数)
ceil 天花板(逢小数进1)
round 四舍五入
random 随机
abs absolute 绝对值

js里自带一些对象,供我们开发者使用,这些对象提前内置准备好了一些常用的属性和方法,我们直接拿来用就可以了。

比如:圆周率 3.1415926 Math.PI

Math内置对象 不是一个构造函数 所以直接使用不需要new

Math.PI 直接使用,不需要创建

console.log(Math.PI)//3.1415926
Math.max() / Math.min()
返回一组数字中的最大/小值,如果给定的参数中至少有一个参数无法转换为数字则返回NaN。

console.log(Math.max(10,22,5));//22
console.log(Math.max(10,'a',5));//NaN

console.log(Math.min(10,22,5));//5
console.log(Math.min(10,'a,5));//NaN
取整函数
Math.floor 向下取整

console.log(Math.floor(1.1));//1
console.log(Math.floor(1.5));//1
console.log(Math.floor(1.9));//1

console.log(Math.floor(-1.1));//-2
console.log(Math.floor(-1.5));//-2
console.log(Math.floor(-1.9));//-22、
Math.ceil向上取整

console.log(Math.ceil(1.1));//2
console.log(Math.ceil(1.5));//2
console.log(Math.ceil(1.9));//2

console.log(Math.ceil(-1.1));//-1
console.log(Math.ceil(-1.5));//-1
console.log(Math.ceil(-1.9));//-1
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

//.5谁大取谁
console.log(Math.round(1.5));//2
console.log(Math.round(-1.5));//-1
Math.random生成随机数(重点)
返回的是0~1之间的随机小数 [0,1)

这个随机函数括号之间不写参数

console.log(Math.random());
得到一个两个数之间的随机整数,包括两个数在内的方法:

function getRandom(min,max){
return Math.floor(Math.random()*(max-min+1))+min;
}
console.log(getRandom(0,5));
案例:随机生成背景颜色

<style>
body {
background-color: rgb(0, 255, 0);
}
</style>

<script>
function getRandom(min,max){
return Math.floor(Math.random()*(max-min+1))+min;
}
console.log(getRandom(0,5));
function getRandomColor(){
var c1=getRandom(0,255);
var c2=getRandom(0,255);
var c3=getRandom(0,255);
return 'rgb(' + c1 + ',' + c2 + ',' + c3 + ')'
}
console.log(getRandomColor());

// 下面的代码演示写的程序没有错误

window.onload = function() {
document.body.style.backgroundColor = getRandomColor();
}
</script>
Math.abs()
alert(Math.abs(-1)); //1

alert(Math.abs('1'));//1 隐式转换 讲字符型转换为数值型 再取绝对值

alert(Math.abs('abs'));//NaN 如果里面参数 有非数字型的 字符串 返回的结果是 NaN

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 俗语说“好吃不过饺子,舒服不过躺着”,很多人觉得劳累时躺着最解乏。但其实,人体最喜欢的姿势既不是躺,也不是...
    许愿_7d09阅读 1,872评论 0 0
  • 秋草蔓延荒园径 弯沿奇曲不见头 风吹草动来时路 没入丛中无影踪
    平平_0c01阅读 1,436评论 0 5
  • 董沛沛 洛阳 焦点讲师班三期 坚持原创分享第八十八天 这个暑假一直在坚持每日一课,读到现在,两本书都已接近尾...
    缘源流长阅读 1,105评论 0 0
  • 源码传送门react-native-webview-plugin插件 在开发Android的时候,一般我们会有一些...
    Code4Android阅读 52,172评论 23 21
  • 俗话说的好 “工欲善其事,必先利其器”,想必Android Studio(后面简称AS)已成为主流标准的开发工具了...
    Zyao89阅读 5,190评论 0 5