概述
Math对象的用法
Math对象在JS中常常处理一些数学数值的问题
Math对象并不像Date和String那样是对象的类,因此没有构造函数Math(),像Math.abs()这样的函数只是函数,不是某个对象的方法。因此,我们不需要创建它,可以直接把它作为对象直接使用就可以调用它的所有属性和方法。
//对于负数取正处理,取绝对值
let mun = -1;
mun = Math.abs(mun);
console.log(mun)
//输出 1
//对于输出反余弦值的处理
let mun = 1; //注意mun不能大于1,否则输出NaN
mun = Math.acos(mun);
console.log(mun)
//输出 0
//对于输出反正弦值的处理
let mun = 0; //注意mun不能大于1,否则输出NaN
mun = Math.asin(mun);
console.log(mun)
//输出 0
//对于输出反正切值的处理
let mun = 0;
mun = Math.atan(mun);
console.log(mun)
//输出 0
//对于坐标角度的处理
let x = 1;
let y = 0;
angle = Math.atan2(y,x);
//输出从x轴到点(x,y)的角度
console.log(angle)
//输出 0
//对数进行上舍入取整
let mun = 0.01;或者 let num = 0.99
mun = Math.ceil(mun);
console.log(mun)
//都是输出 1,向上取整的意思
//对数进行下舍入取整
let mun = 1.01;或者 let num = 1.99
mun = Math.floor(mun);
console.log(mun)
//都是输出 1,向下取整的意思
//返回数的余弦值
let mun = 0;
mun = Math.cos(mun);
console.log(mun)
//输出 1
//返回数的正弦值
let mun = 0;
mun = Math.sin(mun);
console.log(mun)
//输出 0
//返回角的正切值
let mun = 0;
mun = Math.tan(mun);
console.log(mun)
//输出 0
//返回e的指数
let mun = 0;
mun = Math.exp(mun);
console.log(mun)
//输出 1
//返回数的自然对数(底为e)
let mun = 1;
mun = Math.log(mun);
console.log(mun)
//输出 0
//返回数的平方根
let mun = 4;
mun = Math.sqrt(mun);
console.log(mun)
//输出 2
//四舍五入取整
let x = 1.4;
let y = 1.6;
x = Math.round(x);
y = Math.round(y);
console.log(x)//输出 1
console.log(y)//输出 2
//求x的y次幂
let x = 2;
let y = 2;
mun = Math.pow(x,y);
console.log(mun)
//输出 4
//一组数的最高值和最低
x = Math.max(1,2,3,4,5,6,7,8,9);
y = Math.min(1,2,3,4,5,6,7,8,9);
console.log(x)//输出 9
console.log(y)//输出 1
//取随机数
num = Math.random()
console.log(num)
//输出0-1之间的随机数
//指定某个区间内取随机数
let min = 1;
let max = 9;
//先对两个数求差值
diff = max - min;
//差值乘以随机数 加最小值 可得
rand = diff * Math.random() + min
console.log(rand)
//输出1-9之间的随机数
//如果取整数的话,只需要四舍五入就行
rand = Math.round(diff * Math.random()) + min
console.log(rand)
//输出1-9之间的随机整数
最后
以上就是甜蜜鼠标为你收集整理的Math对象的用法的全部内容,希望文章能够帮你解决Math对象的用法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复