絕對值Math.abs()
console.log(Math.abs(-25));
console.log(Math.abs('-25'));//存在隱式轉換可以求絕對值
console.log(Math.abs('wq'));//結果為NaN not a number
取整Math.floor() Math.ceil()
console.log(Math.floor(1.9)); 向下取整 floor意為地板
console.log(Math.ceil(1.1)); 向上取整 ceil意為天花板
四舍五入Math.round()
console.log(Math.round(1.5)); 結果為2
console.log(Math.round(-1.5)); 注意當以 .5 結束時,結果往較大數取,所以此結果為-1
隨機數函數Math.random()
function getRandom(min,max){
return Math.floor(Math.random()*(max-min+1))+min; //隨機整數
}
console.log(Math.random()); //o到1(包含0)的隨機小數
console.log(getRandom(1,10));
一個猜數字的小游戲
var m=getRandom(1,50); //生成1到50之間的隨機數 for(var i=10;i>0;i--) { var n=prompt('請輸入你猜的1-50數字呀'); if(i>1){ if(m<n){ alert('你猜大了,'+'還有'+(i-1)+'次機會哦!'); } else if(m>n){ alert('你猜小了,'+'還有'+(i-1)+'次機會哦!'); } else if(m=n){ alert('你真棒,猜對了'); break; } }else{ alert('機會用完了哦!'); } }