JS中Math函数的常用方法

JavaScript013

JS中Math函数的常用方法,第1张

JS中Math函数的常用方法

Math是数学函数,但又属于对象数据类型typeof Math=>‘object’

console.dir(Math)查看Math的所有函数方法。

1,Math.abs()获取绝对值

Math.abs(-12) = 12

2,Math.ceil() and Math.floor()向上取整和向下取整

console.log(Math.ceil(12.03))//13

console.log(Math.ceil(12.92))//13

console.log(Math.floor(12.3))//12

console.log(Math.floor(12.9))//12

3,Math.round()四舍五入

注意:正数时,包含5是向上取整,负数时包含5是向下取整。

1、Math.round(-16.3) = -16

2、Math.round(-16.5) = -16

3、Math.round(-16.51) = -17

4,Math.random()取[0,1)的随机小数

案例1:获取[0,10]的随机整数

console.log(parseInt(Math.random()*10))//未包含10

console.log(parseInt(Math.random()*10+1))//包含10

案例2:获取[n,m]之间的随机整数

Math.round(Math.random()*(m-n)+n)

5,Math.max() and Max.min()获取一组数据中的最大值和最小值

console.log(Math.max(10,1,9,100,200,45,78))

console.log(Math.min(10,1,9,100,200,45,78))

6,Math.PI获取圆周率π 的值

console.log(Math.PI)

7,Math.pow() and Math.sqrt()

Math.pow()获取一个值的多少次幂

Math.sqrt()对数值开方

Math.pow(10,2) = 100

Math.sqrt(100) = 10

在写js中,我们经常遇见 js 随机函数,总结一下最近写验证码的时候  用到过的js 随机函数

Math.random()结果为0-1间的随机数(包括0,不包括1)

Math.floor( n )参数为Number 类型 ,函数结果 为num 的整数部分

Math.round( n ) ; 参数为Number 类型。函数结果 为num 四舍五入部分

Math.ceil( n )参数为Number类型。 函数结果为大于等于n的整数

Math.ceil(Math.random()*10) : 主要获取1到10的随机整数,取0的几率极小。

Math.round(Math.random()) : 可均衡获取0到1的随机整数

Math.round(Math.random()*10)  可基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半

Math.floor(Math.random()*10) 可均衡获取0到9的随机整数

例子:

    1. 实现一个 随机 汉字

         randomChi(){   // 随机生成汉字

                return `\\u${Math.round(Math.random() * 20901 + 19968 ).toString(16)}`

           }

    2. 实现一个n - m 的整数 ( 参照于 http://www.jb51.net/article/56019.htm )

        生成 n-m , 包含n 但不包含 m的整数

            第一步算出 m -n的值,假设等于 w 

            第二步 Math.random( )  * w

            第三步 Math.random() * w +n

            第四步 parseInt( Math.random() * w +n, 10)

         生成一个 n-m ,包含 m 但不包含 n的整数

            第一步算出 m-n的值,假设等于w

            第二步Math.random()*w

            第三步Math.random()*w+n

            第四步Math.floor(Math.random()*w+n) + 1

         生成一个不包含 n -m 但都不包含 n  和 m

             第一步算出 m-n-2的值,假设等于w

              第二步Math.random()*w

              第三步Math.random()*w+n +1

               第四步Math.round(Math.random()*w+n+1) 或者 Math.ceil(Math.random()*w+n+1)

            生成n-m,包含n和m的随机数:

                第一步算出 m-n的值,假设等于w

                第二步Math.random()*w

                第三步Math.random()*w+n

                第四步Math.round(Math.random()*w+n) 或者 Math.ceil(Math.random()*w+n)

             实例: 生成800-1500的随机整数,包含800但不包含1500

                1500-800 = 700

                Math.random()*700

                var num = Math.random()*700 + 800

                num = parseInt(num, 10)

更多实例 请查看  https://github.com/Mrangmaomao

是26,js中的math对象用来执行数学任务,这个对象有很多属性和方法,其中ceil方法用来对某个小数向上取整,即不管小数点后面的数据是什么都会向前进一,并且把小数舍弃,也叫上舍入,题目中25.5进行上舍入之后就是26。其实还可以这样记:ceil是天花板的意思,天花板在我们头顶,所以要向上取整,而floor是地板的意思,所以要向下取整。希望对你有用