2013-12-21 188 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);