JavaScript--Math对象

JavaScript–Math对象
开发工具与关键技术: Visual Studio 2015 – JavaScript
作者:廖亚星
撰写时间:2019年 4月 30日

Math 对象用于执行数学任务。
使用 Math 的属性和方法的语法:
var pi_value=Math.PI;
var sqrt_value=Math.sqrt(15);
Math 对象并不像 Date 和 String 那样是对象的类,因此没有构造函数 Math(),像 Math.sin() 这样的函数只是函数,不是某个对象的方法。您无需创建它,通过把 Math 作为对象使用就可以调用其所有属性和方法。
JavaScript--Math对象
JavaScript--Math对象
获取π
var pi=Math.PI;
document.write(“π的值大约是:”+pi+"");
浏览器返回值:
JavaScript--Math对象
计算绝对值
var a=Math.abs(-1550);
document.write("-1550的绝对值:"+a+"");
浏览器返回值:
JavaScript--Math对象
次幂运算
document.write(“2的平方:”+Math.pow(2,2)+"");
document.write(“2的3次方:”+Math.pow(2,3)+"");
document.write(“2的4次方:”+Math.pow(2,4)+"");
document.write(“2的10次方:”+Math.pow(2,10)+"");
浏览器返回值:
JavaScript--Math对象
最大值和最小值
document.write(“最大值:”+Math.max(655,5656,223,4,2,269854,89189,152)+"");
document.write(“最小值:”+Math.min(655,5656,223,4,2,269854,89189,152)+"");
浏览器返回值:
JavaScript--Math对象
取近似值
round()函数是取最接近整数,如果遇到一样近,则取最大值
正数的round()是四舍五入;负数的round()则可理解为“五舍六入”。
正数:
var z =5.6;
document.write(“5.6进行上舍入:”+Math.ceil(z)+"");
document.write(“5.6进行下舍入:”+Math.floor(z)+"");
document.write(“5.6进行round():”+Math.round(z)+"");
浏览器返回值:
JavaScript--Math对象
负数:
z=-5.6
document.write("-5.6进行上舍入:"+Math.ceil(z)+"");
document.write("-5.6进行下舍入:"+Math.floor(z)+"");
document.write("-5.6进行round():" + Math.round(z) + “”);
document.write("-5.5进行round():" + Math.round(-5.5) + “”);
浏览器返回值:
JavaScript--Math对象
随机数
document.write(“0~1的随机数:”+Math.random()+"");
document.write(“0~10的随机数:” + (Math.random() * 10) + “”);
document.write(“2~6的随机数:” + (2+Math.random() * 4) + “”);
浏览器返回值:
JavaScript--Math对象