干货分享 -- Math

昼猫笔记 JavaScript -- Math

Math也是JS的内置对象,但是它不是一个构造函数,它属于一个工具类不用创建对象,它封装了数学运算相关的属性和方法,今天就来写下常用的函数【API(application progrom interface 应用程序开发接口)】


 

常用属性

PI 表示的圆周率



 

常用方法

abs() 可以用来计算一个数的绝对值

console.log(Math.abs(-1)) // 1

round() 四舍五入取整

console.log(Math.round(3.22)) // 3

ceil() 向上取整,获取最接近的整数(大于或者等于当前数字)

console.log(Math.ceil(3.000022)) // 4
console.log(Math.ceil(3)) // 3

floor() 向下取整

console.log(Math.floor(3.22)) // 3

max() 取最大值

console.log(Math.max(3,4,6,7,2,1,4,0)) // 7

min() 取最小值

console.log(Math.min(3,4,6,7,2,1,4,0)) // 0

获取数组中最大数,最小数

var arr = [3, 4, 6, 7, 2, 1, 4, 0]
console.log(Math.max.apply(null, arr)) // 7
console.log(Math.min.apply(null, arr)) // 0

pow() 获取指定数字的次方

console.log(Math.pow(2,3)) // 8

sqrt() 获取指定数的平方根

console.log(Math.sqrt(144)) // 12

random() 返回0~1之间的随机数(不包含0、1)

console.log(Math.random())
console.log(Math.round(Math.random()*10)) // 0~10之间的随机数

随机色

function bg(){
    var r=Math.floor(Math.random()*256);
    var g=Math.floor(Math.random()*256);
    var b=Math.floor(Math.random()*256);
    return "rgb(" + r +','+ g +','+ b +")";
}

猜你喜欢

转载自www.cnblogs.com/zhoumao/p/10233981.html