JS Math

Math对象是JS内置对象,提供一系列数学常数和数学方法。Math对象只提供了静态属性和方法,不用实例化。
有时候涉及到数学运算,就可以用它。

Math
E:
2.718281828459045
LN2
:
0.6931471805599453
LN10
:
2.302585092994046
LOG2E
:
1.4426950408889634
LOG10E
:
0.4342944819032518
PI
:
3.141592653589793
SQRT1_2
:
0.7071067811865476
SQRT2
:
1.4142135623730951

Math.PI
3.141592653589793
Math.PI*3*3                                   //算圆的面积
28.274333882308138

方法

  • round四舍五入
Math.round(4.3)
4
Math.round(-4.3)
-4
Math.round(-4.5)                //不是-5,往大处入。
-4
Math.round(4.6)
5
Math.round(4.5)
5
Math.round(0)
0
  • abs,max,min
    abs求绝对值
Math.abs(-4)
4
Math.max(2,-3,6)
6
Math.min(2,-3,6)
-3
Math.min(-3,-3,-3)
-3
Math.min(-3,-3,'g')
NaN

如何求数组里的最大值和最小值(记住就行):

Math.max.apply(null,[3,-3,2,6,8])
8
Math.min.apply(null,[3,-3,2,6,8])
-3

floor,ceil

floor是返回小于参数值的最大整数:

Math.floor(3.2)
3
Math.floor(-3.2)
-4

ceil返回以大于参数的最小整数

Math.ceil(3.2)
4
Math.ceil(-3.2)
-3
Math.ceil(-3.8)
-3

pow ,sqrt

pow(x,y)就是返回x的y次幂:

Math.pow(2,2)
4
Math.pow(2,3)
8

sqrt返回参数的平方根,负数则返回NaN

Math.sqrt(4)
2
Math.sqrt(-44)
NaN

log,exp

log返回以e为底的自然对数:

Math.log(Math.E)
1
Math.log(10)
2.302585092994046

Math.log(100)/Math.LN10
2                                     //以10为底
Math.log(8)/Math.LN2
3                //以2为底
Math.exp(1)
2.718281828459045                //返回e的参数次方
Math.exp(1)  ===Math.E
true
Math.exp(3)  
20.085536923187668

random

返回0到1之间的一个伪随机数,可能等于0,但一定小于1.

Math.random
function random() { [native code] }
Math.random()
0.2951290495662988
Math.random()
0.2444609277534875
Math.random()
0.5542942123798398
Math.random()*100
47.47271738517216
Math.random()*100
87.89817118274796
Math.floor(Math.random()*100)
25
Math.floor(Math.random()*100)
56
Math.floor(Math.random()*100)
91
Math.floor(Math.random()*5)
3
Math.floor(Math.random()*5)
4
Math.floor(Math.random()*5)
2
Math.floor(Math.random()*5)
2
Math.floor(Math.random()*5)
1
Math.floor(Math.random()*5)
2
Math.floor(Math.random()*5)
2
Math.floor(Math.random()*10)+10
14
Math.floor(Math.random()*10)+10
14

获取一个随机的字符串:

function randomStr(len){
  var str=''
  var dict='abcdefghijklmnopqrstuvwxyz_0123456789'
  
  for(var i=0;i<len;i++){
    var index=Math.floor(Math.random()*dict.length)
    str += dict[index]
  }
  return str
}
var str = randomStr(32)
console.log(str)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Math Math对象是JavaScript的内置对象,提供一系列数学常数和数学方法。Math对象只提供了静态的属...
    李诺哦阅读 291评论 0 0
  • 二、 Math对象 Math主要做一些数学上的常用运算:比如平方、绝对值、开方、三角函数等。 2.1 常用属...
    壬万er阅读 243评论 0 0
  • Math对象包含的属性大部分是数学计算中可能会用倒的一些特殊值: 向上舍入小数点,它将数值向上舍入为最接近的整数M...
    闫子扬阅读 409评论 0 0
  • Math 1.写一个函数,返回从min到max之间的 随机整数,包括min不包括max 2.写一个函数,返回从mi...
    饥人谷_bigJiao阅读 578评论 0 0
  • 怀念故乡 星空下捉迷藏 没人告诉你 应该藏在哪 也没人告诉你 必须蹲在大树下
    我要的大晴天阅读 134评论 0 1