2011-11-29 28 views
0

我有這樣的代碼:爲什麼獲取數組的長度不確定?

$.getJSON('newMessageDetails', function (json) 
{ 
    var old_id = document.getElementById("td_id").value; 
    var messages_count = Object.keys(json).length;   
    console.log(messages_count); 
    console.log(json); 
    last_id = json[messages_count]["msgId"]; 

}); 

的JSON [messages_count] [ 「的msgId」]給出在控制檯未定義??

我newMessageDetails:

public function executeNewMessageDetails(sfWebRequest $request) 
{ 
    $profile_id = $this->getUser()->getAttribute('profile_id','zero'); 
    $new_msgs = RcMessageBoxTablePeer::getNewMessages($profile_id); 
    $hr=2; 
    $i=1; 
    if (count($new_msgs) >= 1) 
    { 
     foreach ($new_msgs as $row) 
     { 
      $date = $row->getCreatedAt(); 
      //$cd = strtotime($date); 
      //$newdate = date('Y-m-d H:i:s', mktime(date('h',$cd), date('i',$cd), date('s',$cd), date('m',$cd), date('d',$cd), date('Y',$cd))); 
      $subject = $row->getSubject(); 
      $message = $row->getMessage(); 
      $from = $row->getProfileIdFrom(); 
      $id = $row->getId(); 
      $uc_record = RcProfileTablePeer::getById($from); 
      $uc_from = $uc_record->getUniqueCode(); 
      $output[$i] = array("td_date" => $date, "td_subject" => $subject, "td_from" => $uc_from, "td_message" => $message, "msgId" => $id , "i" => $i); 
      $i++; 
     } 
     return $this->renderText(json_encode($output)); 
    } 
} 

的console.log(JSON)給出:

5 
list:98 
Object 
543: Object 
544: Object 
545: Object 
546: Object 
547: Object 
i: 1 
msgId: 547 
td_date: "2011-11-29 11:33:05" 
td_from: "CHARLIE000RC" 
td_message: "tooltip show message test 2 id 547" 
td_subject: "Freechat message" 

可一些,一個解釋嗎?不知道什麼即時做錯了雖然 謝謝

+0

可能重複的[對象填充對象的長度?](http://stackoverflow.com/questions/5545426/length-of-an-object-filled-with-objects) – Quentin

回答

0

如果您想所有關鍵字的計數,你就能把重寫這樣:

$.getJSON('newMessageDetails', function (json) 
{ 
    ...; 
    var messages_count = Object.keys(json).length;   
    console.log(messages_count); 
}); 
1

對象沒有長度屬性。嘗試這個。

var obj = jQuery.parseJSON(json); 

obj.length(); 

或者你可以試試這個。

Object.keys(json).length; 
+0

如果長度屬性未定義,那麼它不會包含可以調用的函數。 – Quentin

+0

yikes是很正確的,但現在我得到:Uncaught TypeError:不能調用方法的'長度'null –

0

你應該只通過對象迭代和計數。這是你真正瞭解你的物體中有多少「有意義」的物體的唯一方法。