亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

javascript中內(nèi)置對象Math的介紹及用法案例

 更新時間:2022年03月09日 16:22:28   作者:館主阿牛  
Math對象是一個內(nèi)置對象,具有數(shù)學(xué)常數(shù)和函數(shù)的屬性和方法,不是一個函數(shù)對象,下面這篇文章主要給大家介紹了關(guān)于javascript中內(nèi)置對象Math的介紹及用法案例的相關(guān)資料,需要的朋友可以參考下

前言

今天總結(jié)一下javascript 內(nèi)置對象Math中的函數(shù)用法,順帶寫一下常見的案例。

Math概述

Math 對象不是構(gòu)造函數(shù),它具有數(shù)學(xué)常數(shù)和函數(shù)的屬性和方法。跟數(shù)學(xué)相關(guān)的運算(求絕對值,取整、最大值等)可以使用 Math 中的成員。

Math中常用函數(shù)的用法

Math.PI //圓周率
Math.floor () //向下取整
Math.ceil () //向上取整
Math.round () //四舍五入就近取整 注意﹣3.5 結(jié)果是-3
Math.abs () //絕對值
Math.max ()/Math.min() //求最大值和最小值
Math.random() //返回一個隨機的小數(shù) 0=<x<1(這個方法里面不跟參數(shù))

1.絕對值方法

 //1.絕對值方法
        console.log(Math.abs(1)); // 1
        console.log(Math.abs(-1));  //1
        console.log(Math.abs('-5')); //5  會隱式轉(zhuǎn)換,將數(shù)字字符串轉(zhuǎn)換為數(shù)字,然后取絕對值
        console.log(Math.abs('aniu')); // NaN

2.三個取整方法

//2.三個取整方法
        console.log(Math.floor(1.1)); //1
        console.log(Math.floor(1.9)); //1
        console.log(Math.floor(-1.1)); //-2

        console.log(Math.ceil(1.1));  // 2
        console.log(Math.ceil(1.9)); //2
        console.log(Math.ceil(-1.9)); //-1

        console.log(Math.round(1.5)); //2 四舍五入 .5這個特殊,是往大了取
        console.log(Math.round(-1.5)); // -1  往大了取
        console.log(Math.round(-1.2));  // -1

3.求最大值/最小值

//3.求最大值/最小值
        console.log(Math.max(1,5,78,46));
        console.log(Math.min(1,5,78,46));

4.隨機數(shù)

 //4.隨機數(shù)
        console.log(Math.random());

案例-求兩個數(shù)之間的隨機整數(shù)的小算法(重要)

求兩個數(shù)之間的隨機整數(shù) 并且包含這兩個數(shù):
//核心算法
Math.floor(Math.random()*(max-min)) + min;

function getRandom(min,max){
            return Math.floor(Math.random()*(max-min)) + min;
        }

        console.log(getRandom(1,7));

案例-隨機點名(嘿嘿嘿)

//隨機點名
  var arr = ['阿牛','夢夢','小鳴人','winter','小何','WA','賤神','扎哇']  //太多啦,就寫這些舉例啦
  console.log(arr);
  console.log('阿牛愛你們??????');
  function getRandom(min,max){
          return Math.floor(Math.random()*(max-min)) + min;
       }

  console.log('隨機點中了:' + arr[getRandom(0,arr.length - 1)]);

補充案例

要求:得到兩個數(shù)之間的隨機整數(shù),并且包含這兩個數(shù)

var min, max;  //定義最大數(shù)和最小數(shù)
Math.floor(Math.random() * (max - min + 1)) + min;  //返回最大數(shù)和最小數(shù)之間的隨機整數(shù),并且包含最大數(shù)和最小數(shù)

將上述代碼封裝成函數(shù)使用起來更方便

function getNum(min,max){
    return Math.floor(Math.random() * (max-min+1)+min);
}

結(jié)語

到此這篇關(guān)于javascript中內(nèi)置對象Math的文章就介紹到這了,更多相關(guān)javascript內(nèi)置對象Math案例內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論