2009-05-28 63 views
33

的代碼:使用可變密鑰使用在JavaScript中值的對象

function updateDashboardData() { 
    $.getJSON("includes/system/ajaxDataInterface.php", {recordcount:1}, function(data) { 
     $('.stationContainer').each(function(data) { 
      var bsID = $(this).attr("id"); 
      var bsStatus = $(this).children('.stationStatus'); 
      alert(data[bsID][0].time); 
      bsStatus.find('.bs_maxHandsets').text(data[bsID][0].maxHandsets); 
      bsStatus.find('.bs_time').text(data[bsID][0].time); 
     }); 
    }); 
} 

對象數據:

{ 
    "A5A50000": [{ 
     "bsid": "A5A50000", 
     "chanCount": 17, 
     "time": "2009-05-27 16:36:45", 
     "avgInterference": 1.711765, 
     "maxInterference": 4.97, 
     "avgHandsets": 205.1176, 
     "maxHandsets": 315, 
     "avgCalls": 6.4118, 
     "maxCalls": 13, 
     "avgCBA": 3868.98059, 
     "maxCBA": 7463, 
     "sumSuccessCBA": 197318, 
     "sumTimeoutHandoff": 133, 
     "sumAttemptHandoff": 1028, 
     "sumDeniedHandoff": 216, 
     "sumConfirmHandoff": 679, 
     "sumHandoffNetwork": 61873, 
     "sumJoinNetwork": 96888, 
     "sumLeaveNetwork": 93754, 
     "sumRcvdKeepalive": 98773, 
     "sumTimeoutKeepalive": 19748, 
     "sumAttemptUplink": 93689, 
     "sumBlockedUplink": 62453 
    }] 
} 

問題:

alert(data.A5A50000[0].time);正確地顯示「2009-05-27 16 :36:45" 。

alert(bsID);正確顯示「A5A50000」。

alert(data.bsID[0].time);報告「data.bsID未定義」。

alert(data[bsID][0].time);報告「數據[bsID]未定義」。

當變量未被評估時,我有點不清楚。也許我忽略了一些愚蠢的東西,但我無法弄清楚我的問題在這裏。

+0

嗯,我也測試它和它的作品對我.. – 2009-05-28 19:22:05

+0

如果你提醒(bsID)會發生什麼;?它被定義了嗎? – 2009-05-28 19:31:32

+1

警報(bsID)報告「A5A50000」。 上面更新了原始的updateDashboardData()函數。當我通過updateDashboardData()從控制檯啓動函數時;我迎接:「數據[bsID]未定義 http://192.168.2.236/michaelg/js/xmonitor.js 第21行」。第21行是alert()。最初的代碼和我在這裏如何應用它可能會影響結果之間有什麼功能不同? – mikegreenberg 2009-05-28 19:34:09

回答

88

您可以通過點符號或括號符號來訪問對象屬性。

var x = {'test': 'hi'}; 
alert(x.test); // alerts hi 
alert(x['test']); // alerts hi 

當你有一個動態值,你必須使用後者:

var property = 'test'; 
alert(x.property); // looks for x.property, undefined if it doesn't exist 
alert(x[property]); // looks for x['test'], alerts hi 

所以,你真正想要的是:

alert(data[bsID][0].time); 

編輯

不知道你在做什麼錯,但是這對Firebug公司來說是有用的nsole:

var data = {"A5A50000":[{"bsid":"A5A50000","chanCount":17,"time":"2009-05-27 16:36:45","avgInterference":1.711765,"maxInterference":4.97,"avgHandsets":205.1176,"maxHandsets":315,"avgCalls":6.4118,"maxCalls":13,"avgCBA":3868.98059,"maxCBA":7463,"sumSuccessCBA":197318,"sumTimeoutHandoff":133,"sumAttemptHandoff":1028,"sumDeniedHandoff":216,"sumConfirmHandoff":679,"sumHandoffNetwork":61873,"sumJoinNetwork":96888,"sumLeaveNetwork":93754,"sumRcvdKeepalive":98773,"sumTimeoutKeepalive":19748,"sumAttemptUplink":93689,"sumBlockedUplink":62453}]}; 
var bsID = 'A5A50000'; 
alert(data[bsID][0].time); 
3

在Javascript中,您可以使用對象或數組式樣的表示法來查找屬性。以下是等價的:

data.A5A50000 
data['A5A50000'] 

有了第二個語法,你可以將對象的字符串中使用變量:

data[bsID][0]