JS取整取餘,Math對象的操作方法

所有方法都是屬於Math對象的方法

取整

取整

//丟棄小數部分,保留整數部分
parseInt(7/2);  //3

向上取整

//向上取整,有小數就整數部分+1
Math.ceil(7/2);  //4

向下取整

//向下取整,丟棄小數部分
Math.floor(7/2);  //3

四捨五入

//四捨五入
Math.round(7/2);  //4

取餘

取餘

//取餘
7%2;  //1

取最大值和最小值的方法

Math對象中的min()和max()方法可以用於確定一個數組中的最大值和最小值

let max = Math.max(3, 54, 62, 10);
console.log(max);  //62
let min = Math.min(3,54,62,10);
console.log(min);  //3
//對於一個確定的數組,需要使用apply來改變this指針來指向Math對象而不是window對象
let arr = [3,54,62,10];
let max = Math.max.apply(Math,arr);
console.log(max);  //62

random()—取隨機數

Math.random()方法返回一個大於等於0而小於1 的一個隨機數

let random = Math.random(); // [0,1)

//獲取一個1~10之間的整數
let random = Math.floor(Math.random()*10+1);

//編寫一個函數,輸入取值範圍能夠輸出一個在該範圍內的隨機數
function selectFrom(lowerValue, upperValue){
    let choices = upperValue - lowerValue;
    return Math.floor(Math.random()*choices + lowerValue);
}
let num = selectFrom(2,10);
console.log(num);  //輸出一個2~10(包括2和10)的一個數值

let colors = ['red', 'green', 'blue', 'yellow', 'black', 'purple'];
let color = colors[selectFrom(0,colors.length-1)];
console.log(color); //隨機輸出一個顏色

toFixed()方法

number.toFixed(num)方法會將number轉換爲num個小數位的小數,其中num是必需值,如果省略了該值,將用0代替

let num = 12.3335;
console.log(num.toFixed(2));  //12.33
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章