JavaScript Math对象
2021-10-16 本文已影响0人
微语博客
JavaScript Math对象提供了一些常见数值和一些常用的算术函数。
Math对象
Math 对象用于执行数学任务,Math 对象并不像 Date 和 String 那样是对象的类,因此没有构造函数 Math(),不能使用new方法生成对象。
var x = Math.PI;//返回常数PI
console.log(x);//3.141592653589793
var y = Math.sqrt(16);//返回16的平方根
console.log(y);//4
随机数的应用
JavaScript Math对象的random函数返回一个0到1区间的随机数,在编程乃至生活中,我们很多地方都会用到随机数。
- 根据概率随机生成布尔值,可以自动生成布尔值,可设置真假值的概率。
function randBool(percent=0.5){
return Math.random() < percent ? true : false;
}
console.log(randBool());//随机输出true或false,概率一样
console.log(randBool());//
console.log(randBool());//
- 根据上下限生成随机数,生成两个数之间的随机数。
function randCross(min,max){
return Math.floor(Math.random()*(max+1-min)+min);
}
console.log(randCross(5,10));//输出5到10之间的随机数
console.log(randCross(5,10));//
console.log(randCross(10,50));//
- 随机生成指定字符。
function randChar(length,chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"){
chars=chars.split("");
let result="";
while(result.length<length){result+=chars[Math.round(Math.random()*chars.length) - 1];}
return result;
}
console.log(randChar(5));//随机返回指定区间的5个字符
console.log(randChar(5));//
console.log(randChar(6));//
- 随机输出数组元素。
function randArr(arr){
return arr[(arr.length?Math.round(Math.random()*(arr.length-1)):undefined)];
}
console.log(randArr([1,2,3,true,"Hello"]));//随机输出数组的其中一个
console.log(randArr([1,2,3,true,"Hello"]));
console.log(randArr([1,2,3,true,"Hello"]));
简单的举了几个花生(栗子举完了),同时感谢网友提供的思路。
Math对象常用属性
属性 | 描述 |
---|---|
E | 返回算术常量 e,即自然对数的底数(约等于2.718)。 |
LN2 | 返回 2 的自然对数(约等于0.693)。 |
LN10 | 返回 10 的自然对数(约等于2.302)。 |
LOG2E | 返回以 2 为底的 e 的对数(约等于 1.4426950408889634)。 |
LOG10E | 返回以 10 为底的 e 的对数(约等于0.434)。 |
PI | 返回圆周率(约等于3.14159)。 |
SQRT1_2 | 返回 2 的平方根的倒数(约等于 0.707)。 |
SQRT2 | 返回 2 的平方根(约等于 1.414)。 |
Math对象常用方法
方法 | 描述 |
---|---|
abs(x) | 返回 x 的绝对值。 |
acos(x) | 返回 x 的反余弦值。 |
asin(x) | 返回 x 的反正弦值。 |
atan(x) | 以介于 -PI/2 与 PI/2 弧度之间的数值来返回 x 的反正切值。 |
atan2(y,x) | 返回从 x 轴到点 (x,y) 的角度(介于 -PI/2 与 PI/2 弧度之间)。 |
ceil(x) | 对数进行上舍入。 |
cos(x) | 返回数的余弦。 |
exp(x) | 返回 Ex 的指数。 |
floor(x) | 对 x 进行下舍入。 |
log(x) | 返回数的自然对数(底为e)。 |
max(x,y,z,...,n) | 返回 x,y,z,...,n 中的最高值。 |
min(x,y,z,...,n) | 返回 x,y,z,...,n中的最低值。 |
pow(x,y) | 返回 x 的 y 次幂。 |
random() | 返回 0 ~ 1 之间的随机数。 |
round(x) | 四舍五入。 |
sin(x) | 返回数的正弦。 |
sqrt(x) | 返回数的平方根。 |
tan(x) | 返回角的正切。 |