Math對(duì)象提供了很多的屬性和方法,用于輔助完成復(fù)雜的計(jì)算任務(wù)鸵闪。
Math.min()
用于一組數(shù)據(jù)中的最小值:
例子:
var a = Math.min(1,2,3,4);
console.log(a); //表示最小值是1
Math.max()
用于一組數(shù)據(jù)中的最大值
例子:
var a = Math.min(1,2,3,4);
console.log(a); //表示最大值是4
舍入方法
Math.ceil() 執(zhí)行向上舍入檐晕,即它總是將數(shù)值向上舍入為最接近的整數(shù);(向上取整)
例子:
var a = Math.ceil(3.14) //向上取整
console.log(a);
Math.floor() 執(zhí)行向下舍入蚌讼,即它總是將數(shù)值向下舍入為最接近的整數(shù)辟灰;(向下取整)
例子:
var a = Math.floor(3.14) //向下取整
console.log(a);
-
Math.round() 執(zhí)行標(biāo)準(zhǔn)舍入,即它總是將數(shù)值四舍五入為最接近的整數(shù)篡石;(四舍五入)
例子: var a = Math.round(3.39) //四舍五入芥喇。 console.log(a);
例子:
var a = Math.round(3.499999999999999999)
console.log(a);
var a = Math.round(3.499999999999999999) //特殊情況。輸出結(jié)果為4
Math.random()方法
返回大于等于0小于1的隨機(jī)數(shù)凰萨。0 <= X < 1
封裝一個(gè)方法:隨機(jī)生成n到m的隨機(jī)數(shù)继控。
function random(n,m){
var num = m - n + 1 ;
return Math.floor(Math.random()*num+n);
}
console.log (random(0,10));//隨機(jī)生成0-10的整數(shù)