標籤:art 實現 one mat 它的 cti i++ 編寫 max
一,Global對象
Global(全域)對象是ECMAScript中一個特別的對象,因為這個對象是不存在的。在ECMAScript中不屬於任何其他的屬性和方法,都屬於它的屬性和方法。所以,事實上,並不存在全域變數和全域函數;所有在全域範圍定義的變數和函數,都是Global對象的屬性和方法。
ECMAScript沒有定義怎麼調用Global對象,所以,Global.屬性或者Global.方法()都是無效的。
(Web瀏覽器將Global作為window對象的一部分加以實現)
Global對象有一些內建的屬性和方法。
var box = ‘//Lee 李‘;
//alert(encodeURI(box)); //只編碼中文
//alert(encodeURIComponent(box)); //編碼了特殊字元和中文
var a = encodeURI(box);
var b = encodeURIComponent(box);
alert(decodeURI(a)); //decodeURI解碼
alert(decodeURIComponent(box)); //decodeURIComponent解碼
eval()方法主要擔當一個字串解析器的作用,他只接受一個參數,而這個參數就是要執行的JavaScript代碼的字串。
eval(‘var box = 100‘); //解析了字串代碼
alert(box);
eval(‘alert(100)‘);
eval(‘function box(){return 123}‘); //也可以解析函數
alert(box());
二.Math對象
ECMAScript還為儲存數學公式和資訊提供了一個對象,即Math對象。與我們在JavaScript直接編寫計算功能相比,Math對象提供的計算功能執行起來要快得多。
alert(Math.E);
alert(Math.PI);
//min()和max()方法
alert(Math.min(2,5,8,4,9,2,0,1)); //最小值
alert(Math.max(2,5,8,4,9,2,0,1)); //最大值
//舍入方法
//向上舍入 將數值向上舍入為最接近的整數
alert(Math.ceil(25.9));
alert(Math.ceil(25.5));
alert(Math.ceil(25.1));
//向下舍入 將數值向下舍入為最接近的整數
alert(Math.floor(25.9));
alert(Math.floor(25.5));
alert(Math.floor(25.1));
//標準舍入即四捨五入 將數值四捨五入為最接近的整數
alert(Math.round(25.9));
alert(Math.round(25.5));
alert(Math.round(25.1));
//Math.random()方法返回介於0到1之間一個隨機數,不包括0和1。如果想大於這個範圍的話,可以套用一下公式:
值 = Math.floor(Math.random()*總數+第一個值)
alert(Math.random());
for(var i=0; i<10; i++)
{
document.write(Math.random());
document.write(‘<br />‘);
}
alert(Math.floor(Math.random()*10+1)); //隨機產生1-10之間的任意數
for(var i=0; i<10; i++)
{
document.write(Math.floor(Math.random()*10+1));
document.write(‘<br />‘);
}
//返回5-10之間
for(var i=0; i<10; i++)
{
document.write(Math.floor(Math.random()*10+5)); //範圍5-14之間 10+5-1=14(5-14)
document.write(‘<br />‘);
}
//如果想5-10之間,10-5+1=6
for(var i=0; i<10; i++)
{
document.write(Math.floor(Math.random()*6+5)); //範圍5-10之間 6+5-1=10(5-10)
document.write(‘<br />
‘);
}
//上述方法太麻煩,還需要計算開始值。可以編寫一個函數用於計算開始值
function select(start,end)
{
var total = end-start+1;
return Math.floor(Math.random()*total+start);
}
//計算的時候只要在函數裡寫上開始值和結束值的參數即可。
for(var i=0; i<10; i++)
{
document.write(select(5,10));
document.write(‘<br />
‘);
}
alert(Math.abs(-5)); //返回num的絕對值
alert(Math.sqrt(9)); //返回num的平方根
JS內建對象