【问题标题】:why does getting array length give undefined?为什么获取数组长度给出未定义?
【发布时间】:2011-11-29 08:13:56
【问题描述】:

我有这个代码:

$.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"] 在控制台中给出 undefined??

我的新消息详情:

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"

有人可以解释一下吗?不知道我做错了什么 谢谢

【问题讨论】:

标签: php javascript json symfony1


【解决方案1】:

对象没有长度属性。试试这个。

var obj = jQuery.parseJSON(json);

obj.length();

或者你可以试试这个。

Object.keys(json).length;  

【讨论】:

  • 如果长度属性未定义,那么它不会包含您可以调用的函数。
  • 是的,完全正确,但现在我得到:未捕获的类型错误:无法调用 null 的方法“长度”
【解决方案2】:

如果您想计算所有键的数量,可以将其重写为:

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

【讨论】:

    【解决方案3】:

    您应该只遍历对象并计数。只有这样,您才能真正知道您的对象中有多少“有意义”的对象。

    【讨论】:

      猜你喜欢
      • 2020-04-02
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      • 2019-04-09
      • 2014-11-02
      相关资源
      最近更新 更多