Javascript 的數(shù)組Array,既是一個數(shù)組,也是一個字典(Dictionary)。先舉例看看數(shù)組的用法。
var a = new Array();a[0] = "Acer";a[1] = "Dell";for (var i in a) { alert(i);}
上面的代碼創(chuàng)立了一個數(shù)組,每個元素都是一個字符串對象。然后對數(shù)組進(jìn)行遍歷。注意 i 的結(jié)果為 0 和 1,a[i] 的結(jié)果才為字符串。下面再看一下字典的用法。
var computer_price = new Array();computer_price["Acer"] = 500;computer_price["Dell"] = 600;alert(computer_price["Acer"]);
我們甚至可以同樣象上面那樣遍歷這個數(shù)組(字典)
for (var i in computer_price) { alert(i + ": " + computer_price[i]);}
這里的 i 即為字典的每個鍵值。輸出結(jié)果為:
Acer: 500
Dell: 600
另外 computer_price 是一個字典對象,而它的每個鍵值就是一個屬性。也就是說 Acer 是 computer_price 的一個屬性。我們可以這樣使用它:
computer_price.Acer
再來看一下字典和數(shù)組的簡化聲明方式。
var array = [1, 2, 3]; // 數(shù)組var array2 = { "Acer": 500, "Dell": 600 }; // 字典alert(array2.Acer); // 500
這樣對字典的聲明是和前面的一樣的。在我們的例子中,Acer又是鍵值,也可是作為字典對象的屬性了。
下面再來看看如何對一個對象的屬性進(jìn)行遍歷。我們可以用 for in 來遍歷對象的屬性。
function Computer(brand, price) {
this.brand = brand;
this.price = price;
}
var mycomputer = new Computer("Acer", 500);
for (var prop in mycomputer) {
alert("computer[" + prop + "]=" + mycomputer[prop]);
}
上面的代碼中,Computer有兩個屬性,brand 和 price.所以輸出結(jié)果為:
computer[brand]=Acer
computer[price]=500
上面的這種用法可以用來查看一個對象都有哪些屬性。當(dāng)你已經(jīng)知道Computer對象有一個brand屬性時,就可以用
mycomputer.brand
或 mycomputer[brand]
來獲取屬性值了。
總結(jié):Javascript中的數(shù)組也可以用來做字典。字典的鍵值也是字典對象的屬性。對一個對象的屬性進(jìn)行遍歷時,可以用for in。