JavaScript-Math

2017-02-25  本文已影响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);
    }
上一篇 下一篇

猜你喜欢

热点阅读