javascript或jquery:循环一个多维对象

我刚刚开始使用JSON,我创建了这个例子。

var shows = { "ShowA": { "Date" : "November 3-5, 2011", "Phone" : "111-111-1111", "Location" : "some location", "url" : "http://www.showA.com" }, "ShowB": { "Date" : "January 15-18, 2012", "Phone" : "222-222-2222", "Location" : "another location", "url" : "http://www.showB.com" } }; 

我想出了如何访问每一位信息……即:alert(shows.ShowA.Date);

但是,我无法弄清楚如何循环整个节目对象,以便提醒每个节目和每个节目的属性。 我需要将其更改为数组吗?

任何帮助将不胜感激。

你可以使用for … in循环

 for(var key in shows) { if (shows.hasOwnProperty(key)) { alert(shows[key].Date); } } 

重要的是要注意一个对象没有排序顺序,但数组却没有。 因此,如果您想按日期排序,则需要使用数组。

使用Object.hasOwnProperty也是一种好习惯

 for(show in shows){ console.log(shows[show]); } 

小提琴: http : //jsfiddle.net/maniator/Wp3N9/

不需要额外的库^ _ ^

这是一个很好的简单例子

 /* A program to find how costly ur roommates are */ function myFatRoommates() { /* Multidimentional Object */ var roommates = { ivar: {potatis: 10}, johan: {mango: 20} }; var marketprice = { ica : {potatis: 5, mango: 20}, willys: {potatis: 2, mango:10} } /* variable with self invoking method */ var price = function (foodname, shopname, amount) { return (marketprice[shopname][foodname] * amount).toString(); } /* A loop to decide how much fatties eat */ for (var person in roommates){ // Looping through roommates for(var foodName in roommates[person]){ //looping through the food they eat var amount = roommates[person][foodName]; // getting the amount for food an individual roommate consumes alert(person + " eats " + amount +" "+ foodName + " everyday which costs " + price(foodName, "ica", amount)+ "USD in ICA "+ price(foodName, "willys", amount)+ "USD in Willys"); // Calculating and print out the result } } } myFatRoommates();