欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

前言

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

Math概述

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

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

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

1.絕對(duì)值方法

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

2.三個(gè)取整方法

//2.三個(gè)取整方法
        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這個(gè)特殊,是往大了取
        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());

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

求兩個(gè)數(shù)之間的隨機(jī)整數(shù) 并且包含這兩個(gè)數(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ī)點(diǎn)名(嘿嘿嘿)

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

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

補(bǔ)充案例

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

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

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

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

結(jié)語(yǔ)

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

相關(guān)文章

最新評(píng)論