最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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() //返回一個隨機(jī)的小數(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.隨機(jī)數(shù)

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

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

求兩個數(shù)之間的隨機(jī)整數(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));

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

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

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

補充案例

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

var min, max;  //定義最大數(shù)和最小數(shù)
Math.floor(Math.random() * (max - min + 1)) + min;  //返回最大數(shù)和最小數(shù)之間的隨機(jī)整數(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)文章

最新評論

岗巴县| 股票| 安塞县| 镶黄旗| 油尖旺区| 宁安市| 海阳市| 阳城县| 柳林县| 北辰区| 明水县| 台东市| 阿拉善左旗| 阿巴嘎旗| 寻乌县| 章丘市| 普安县| 凌源市| 苗栗县| 仁布县| 镇原县| 中方县| 将乐县| 兴仁县| 拜泉县| 遂昌县| 晋州市| 浙江省| 锡林郭勒盟| 扶余县| 思茅市| 托克逊县| 铁岭市| 宝兴县| 同德县| 延长县| 万山特区| 灯塔市| 诏安县| 黄龙县| 客服|