JavaScript-Math

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);
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容