JavaScript 能做的事,并不局限于訪問HTML 表單的數據;它還能讓你創建自己的對象――也就是讓你創建儲存于客戶端的數據。你甚至還能建立包含其它對象的對象。
為什么需要這些功能?一個好的理由就是創建數組(array)。簡單來說,數組是一個含有幾組相關信息的表格或數據庫。在下面的例子當中,我們定義了一個叫做taxTable的對象,該對象包含一個數組,而該數組由五個 name 對象實例所組成。這個數組保存五個州的州名,以及它們相關的稅率。然后,當用戶在訂購表單中輸入州名時,我們就在數組中檢查它,并自動應用正確的稅率。
創建一個5x2的數組,與使用一個快速的 if-then 序列來測試州名相比,使用數組似乎還要做額外的工作。不過,隨著條目個數的增加,數組的功能也就變得愈來愈強大。不妨想象有一個擁有五十個州、或五百個銷售區、亦或是五千個城市的表格。有了一個數組,你就能夠一次建立條目列表,然后每當用戶輸入新數據時,就可迅速加以引用這個條目列表。
下面這個特殊的JavaScript 代碼,開始就像我們的計算(calculation)示例一樣。不過這一次,我們并不止于簡單的數學計算:
function state(stateName, stateTax){
//fill the instance with the values passed in
this.name=stateName;
this.tax=stateTax;
//then return the instance of state
return this;
}
上面定義的state() 函數創建了包括州名與稅率的一個州(state)的實例。然而,我們的州此時似乎什么值都沒有。下面我們給它們一些值吧。
function taxTable(){
//the instance of taxTable is filled with
//an array of state objects
this[0]=new state("AZ", 0.04);
this[1]=new state("HI", 0.10);
this[2]=new state("TX", 0.06);
this[3]=new state("NJ", 0.08);
this[4]=new state("", 0.00);
//return the newly created taxTable to
//the calling function
return this;
}
現在,無論taxTable函數何時被調用,我們都創建了五個不同的州實例,分別編號為0到4。這樣一來,我們就創建了一個數組,來保存我們所有的稅率信息?,F在我們需要加以處理一番:
functioncalculateTax(stateValue){
var index=0;
var result=0;
var temp=0;
首先,我們定義一個稱為calculateTax的函數。calculateTax會以初始化一些變量開始。然后,它需要從用戶那里取得一個值:
//while there"s an instance of state
//in the taxGuide array
while (taxGuide[index])
{
//if the state passed in is in the
//taxGuide array
if (stateValue.toUpperCase() == taxGuide[index].name) {
// put the correct tax rate in "result"
result = taxGuide[index].tax;
}
index++;
}
while 循環會持續將用戶的輸入,與稅率表中的所有可能的條目進行比較,直到比完完全部數據。一旦它發現一個匹配(或是沒有匹配),它就將適當的稅率寫入 result 變量中。然后我們可以使用該稅率來計算總量,然后將其加至我們的總額之中。
{
calcTotal();
var temp1 = document.orderForm.totalPrice.value;
// calculate total with tax
var temp2 = (parseFloat(temp1) * (1 + parseFloat(result)));
// chop off extra decimal places
vartotalWithTax = (Math.round(temp2 * 100)) / 100;
// change value in form
document.orderForm.totalPrice.value =
totalWithTax;
}
上面的代碼計算包括稅金在內的全部費用。首先,我們設定變量temp1 的值等于totalPrice表單元素的值。然后,我們再計算稅后總額,并將其值賦給“temp2”。下一行代碼則使用Math.round方法舍去額外的小數位,然后將新的總額賦值給totalWithTax變量。接下來,我們將此總額送回到訂購表單之中。