2013-12-21 283 views
1

告訴我我在這裏失去了什麼。我有以下JavaScript對象。JavaScript對象屬性總是返回undefined

[ { id: '16B0C2FC-A008-4E8A-849B-DB1251C8CABD', 
    handle: '123', 
    userId: 'ABC123'} ] 

當i執行以下

success: function (registration) { 
       console.log(registration); 
       console.log(registration.handle); 

控制檯日誌寫出該對象如上述定義。但是,當我做registration.handle時,我收到一個錯誤,說「未定義」。如果註冊是上述對象,爲什麼registration.handle不起作用?

我錯過了什麼?

+0

除了答案,你可能還需要解析響應, 'JSON.parse'。 –

+1

這個問題似乎是無關緊要的,因爲它對於單個代碼庫來說太具體了。 – jprofitt

回答

4

您有一個包含對象的數組。您嘗試訪問的屬性是對象的成員,而不是數組。

在訪問其屬性之前,您必須先獲取對象的引用。

registration[0].handle 
+0

謝謝!應該看到了。遲到並一直在看它。 – ToddB

1

試試這個

var registration=[ { id: '16B0C2FC-A008-4E8A-849B-DB1251C8CABD', handle: '123', userId: 'ABC123'} ] 

alert(registration[0].handle) 

DEMO

0

那是因爲你有這麼數組訪問它嘗試

registration[0].handle 

CASE 1

registration = [ { id: '16B0C2FC-A008-4E8A-849B-DB1251C8CABD', handle: '123', userId: 'ABC123'} ]; 
console.log(registration[0].handle); 

CASE 2

registration = { id: '16B0C2FC-A008-4E8A-849B-DB1251C8CABD', handle: '123', userId: 'ABC123'}; 
console.log(registration.handle); 
0

您正在訪問的對象的構件。

做到像這樣

success: function(registration) { 
     $.each(registration, function(index, data) { 
      var handle = data.handle; 
      console.log('id is getting now ' + handle); 
     }); 
    } 
1

是的,你首先需要訪問數組元素,那麼你可以找到對象

console.log(registration[0].handle);