javascript學(xué)習(xí)筆記(八) js內(nèi)置對象
2024-05-06 14:21:42
供稿:網(wǎng)友
1.URI方法
encodeURI()和encodeURIComponent()對URI進(jìn)行編碼
encodeURI()不會對本身屬于URI的特殊字符進(jìn)行編碼,如冒號,正斜杠,問好,井字等
encodeURIComponent()會對任何非標(biāo)準(zhǔn)字符進(jìn)行編碼
2.eval() 方法:解釋參數(shù)中的代碼字符串
代碼如下:
var msg = "hello world";
eval("alert(msg)"); //"hello world"
3.Math 對象
Math.E 數(shù)學(xué)中的e的值
Math.PI π的值
Math.SQRT2 2的平方根
Math.abs(num) num的絕對值
Math.exp(num) e的num次冪
Math.log(num) num的自然對數(shù)
Math.pow(num,n) num的n次冪
Math.sqrt(num) num的平方根
Math.acos(x) x的反余弦值
Math.asin(x) x的反正弦值
Math.atan(x) x的反正切值
Math.atan2(y,x) y/x的反正切值
Math.cos(x) x的余弦值
Math.sin(x) x的正弦值
Math.tan(x) x的正切值
4.min()和max()方法
代碼如下:
var max = Math.max(3,45,67,32);
alert(max); //67
var min = Math.min(2,46,74);
alert(min); //2
5.小數(shù)舍入到整數(shù)方法
Math.ceil() 向上舍入
Math.floor() 向下舍入
Math.round() 四舍五入
代碼如下:
alert(Math.ceil(25.1)); //26
alert(Math.ceil(25.5)); //26
alert(Math.ceil(25.9)); //26
alert(Math.round(25.1)); //25
alert(Math.round(25.5)); //26
alert(Math.round(25.9)); //26
alert(Math.floor(25.1)); //25
alert(Math.floor(25.5)); //25
alert(Math.floor(25.9)); //25
6. random() 方法 返回 介于 0~1 的一個隨機(jī)數(shù),不包括0和1
在某一范圍內(nèi)取一個隨機(jī)數(shù)公式:
隨機(jī)數(shù) = Math.floor(Math.random * 總數(shù) + 第一個值) // 總數(shù)=第二個值 - 第一個值
代碼如下:
//取范圍內(nèi)隨機(jī)數(shù)函數(shù)
function selectFrom(lowerValue,upperValue) {
var count = upperValue - lowerValue + 1;
return Math.floor(Math.random() * count +lowerValue);
}
var num = selectFrom(2,10);
alert(num); //介于2~10之間的數(shù)(包括2和10)