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