常用的Math对象

2018-02-03  本文已影响0人  zy懒人漫游

Math.abs(x) 函数返回指定数字 “x“ 的绝对值。
传入一个非数字形式的字符串或者 undefined/empty 变量,将返回 NaN。传入 null 将返回 0。

Math.abs('-1');     // 1
Math.abs(-2);       // 2
Math.abs(null);     // 0
Math.abs("string"); // NaN
Math.abs();         // NaN

Math.floor() 返回小于或等于一个给定数字的最大整数。

Note:  Math.floor() === 向下取整
Math.floor( 45.05); 
// 45 
Math.floor( 4 ); 
// 4 
Math.floor(-45.05); 
// -46 
Math.floor(-45.95); 
// -46

Math.max() 函数返回一组数中的最大值。

Math.max([value1[,value2, ...]]) 
console.log(Math.max(10,20,30));//30

Math.random() 函数返回一个浮点, 伪随机数在范围[0,1),也就是说,从0(包括0)往上,但是不包括1(排除1),然后您可以缩放到所需的范围。实现将初始种子选择到随机数生成算法;它不能被用户选择或重置。他不能被用户选择或重置。

打印出的值是不同的
console.log(Math.random());//0.9770502385918372
console.log(Math.random());//0.9625775894221074
console.log(Math.random());//0.13663420905433665

Math.round() 函数返回一个数字四舍五入后最接近的整数值。

console.log(Math.round(22.4999));//22
console.log(Math.round(22.999));//23
console.log(Math.round(-22.4));//-22
console.log(Math.round(-22.9999));//-23

Math.sqrt() 函数返回一个数的平方根
如果参数 number 为负值,则 sqrt 返回 NaN。

console.log(Math.sqrt(4));//2
console.log(Math.sqrt(81));//9
console.log(Math.sqrt(-81));//NaN

Math.trunc() 方法会将数字的小数部分去掉,只保留整数部分。

Math.trunc(42.84) // 42
上一篇 下一篇

猜你喜欢

热点阅读