js中math常用使用方法

2021-10-23 17:17:59 字數 3229 閱讀 3271

math.min()用於確定一組數值中的最小值。math.max()用於確定一組數值中的最大值。

alert(math.min(2,4,3,6,3,8,0,1,3));                           //最小值

alert(math.max(4,7,8,3,1,9,6,0,3,2)); //最大值

2.捨入方法

math.ceil()執行向上捨入,即它總是將數值向上捨入為最接近的整數;

math.floor()執行向下捨入,即它總是將數值向下捨入為最接近的整數;

math.round()執行標準捨入,即它總是將數值四捨五入為最接近的整數;

例如:

alert(math.ceil(25.9));                                      //26

alert(math.ceil(25.5)); //26

alert(math.ceil(25.1)); //26

alert(math.floor(25.9)); //25

alert(math.floor(25.5)); //25

alert(math.floor(25.1)); //25

alert(math.round(25.9)); //26

alert(math.round(25.5)); //26

alert(math.round(25.1)); //25

3.random()方法隨機數產生的浮點數

math.random()方法返回介於0到1之間乙個隨機數,不包括0和1。如果想大於這個範圍的話,可以套用一下公式:

值 = math.floor(math.random() * 總數 + 第乙個值)

例如:

alert(math.floor(math.random() * 10 + 1));        //隨機產生1-10之間的任意數
for (var i = 0; i<10;i ++)
為了更加方便的傳遞想要範圍,可以寫成函式:

function selectfrom(lower, upper) 

for (var i=0 ;i<10;i++)

基本方法

math.round();向上四捨五入。

math.ceil();向上取整,有小數就整數部分加1 

math.floor(5/2) ;向下取整 

math.abs();返回絕對值;

math.max();返回兩個以上引數的最大值;

math.min();返回兩個以上引數的最小值;

math.pow(,): 冪的運算;  引數:乙個引數底數 二個引數指數   結果是冪的計算數值結果

math.sqrt(): 開方運算      引數:乙個引數,要開方的數字       結果:開方數值

math.pi    圓周率π(屬性)  

整理

//以下幾項是輸出常數,即只能拿出來用,並不能修改(除了random,只不過也不能修改)

console.log(math.e); // 輸出 e=2.718281828459045

console.log(math.pi); // 輸出圓周率 π=3.141592653589793

console.log(math.sqrt2); // 返回乙個常數,2的平方根=1.4142135623730951

console.log(math.sqrt1_2); // 返回乙個常數,0.5的平方根=0.7071067811865476

console.log(math.ln2); // 輸出 2 的自然對數 =0.6931471805599453

console.log(math.ln10); // 輸出 10 的自然對數 =2.302585092994046

console.log(math.log2e); // 輸出 以 2 為底的 e 的對數 =1.4426950408889634

console.log(math.log10e); // 輸出 以 10 為底的 e 的對數 =0.4342944819032518

console.log(math.random()); // 返回介於0和1之間的偽隨機數。產生的偽隨機數介於0和1之間(含0不含1)

//以下幾項是函式操作,當然還可以細分

//以下幾項是對單個數字的操作

var num = 23.34;

console.log(math.ceil(num)); // 返回大於等於num的最小整數 24

console.log(math.floor(num)); // 返回小於等於num的最大整數 23

console.log(math.round(num)); // 返回與num最接近的整數(四捨五入) 23

console.log(math.abs(num)); // 返回num的絕對值 23

console.log(math.exp(num)); // 返回num的指數

console.log(math.log(num)); // 返回num的自然對數(底為e)

console.log(math.sqrt(num)); // 返回乙個數的平方根

//以下是計算量大一些的函式 立方pow max最大值 min最小值

console.log(math.pow(10,3)); // 輸出10的立方 1000

console.log(math.max(2,3,4)); // 返回多個數值引數中最大的那個 4

console.log(math.min(2,3,4)); // 返回多個數值引數中最小的那個 2

Math的使用方法

math 1.以下函式返回 min 包含 max 不包含 之間的數字 function getrndinteger min,max return math.floor math.random max min min 2.以下函式返回 min 包含 max 包含 之間的數字 function getr...

js中math函式的常用方法

math.abs j絕對值 math.ceil 整數 向上取整和向下取整 console.log math.ceil 12.95 13 console.log math.floor 12.3 12 math.round 四捨五入 注意 正數時,包含5是向上取整,負數時包含5是向下取整。math.ra...

JS中Math函式的常用方法

math是數學函式,但又屬於物件資料型別typeof math object console.dir math 檢視math的所有函式方法。1,math.abs 獲取絕對值 math.abs 12 122,math.ceil and math.floor 向上取整和向下取整 3,math.round...