美文网首页
JavaScript-Math

JavaScript-Math

作者: 阿九是只大胖喵 | 来源:发表于2017-02-25 13:44 被阅读0次

Math是数学函数,里面提供了几个操作数字的方法。
Math.abs() -> 取绝对值

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

Math.ceil() -> 向上取整

console.log(Math.ceil(10.1)); // 11

Math.floor() -> 向下取整

console.log(Math.floor(10.1)); // 10

Math.round() -> 四舍五入

console.log(Math.round(10.1)); // 10
console.log(Math.round(10.6)); // 11

Math.max(val, val, ....) -> 求最大值

console.log(Math.max(1,2,3,4)); // 4

Math.min(val, val, ....) -> 求最小值

console.log(Math.min(1,2,3,4)); // 1

Math.random() -> 获取 [0, 1) 之间的随机小数

console.log(Math.random());

获取 [n, m]之间的随机整数

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

例如:

    // 例如:1-10, 14-58
    // 1-10
    console.log(Math.round(Math.random() * (10 - 1) + 1));
    // 14-58
    console.log(Math.round(Math.random() * (58 - 14) + 14));

得到随机数的函数:

   function getRandom(n, m) {
        // 不管传递的是什么,先强转一下,只有两种情况: 数字和NaN
        n = Number(n);
        m = Number(m);
        // 判断,只要两个钟有一个不是有效数字,就返回0-1之间的随机小数
        if (isNaN(n) || isNaN(m)) {
            return Math.random();
        }
        // 如果n比m大了,默认交换位置
        if (n > m) {
            var temp = m;
            m = n;
            n = temp;
        }
        return Math.round(Math.random() * (m - n) + n);
    }

相关文章

  • JavaScript-Math

    Math是数学函数,里面提供了几个操作数字的方法。Math.abs() -> 取绝对值 Math.ceil() -...

  • JS笔记14:数学对象Math

    其他方法多记忆Math Math其他属性或方法:腾讯云-开发者社区-JavaScript-Math[https:/...

  • JavaScript-Math对象

    Math对象是JavaScript的内置对象,提供一系列数学常数和数学方法。Math对象只提供了静态的属性和方法,...

  • JavaScript-Math对象

    本文简单介绍一下JavaScript中常用的Math对象中的方法 Math.PI 返回圆周率 Math.ceil ...

  • JavaScript-Math 对象详解

    在编程过程中,经常会遇到数据的运算处理,如果掌握了常用的数学函数将能极大地提高编程速度,今天就将 JavaScri...

网友评论

      本文标题:JavaScript-Math

      本文链接:https://www.haomeiwen.com/subject/ioagwttx.html