2012-07-05 52 views
0

我试图创建一个node.js聊天应用程序,当有人加入聊天室时,我想将最后100封邮件推送到他们的浏览器。我有node.js添加每个聊天消息作为一个对象与消息的用户名和文本到数组中。当node.js推入对象数组时,它看起来像这样。jquery - 双括号内的对象数组

[ 
    [ 
     { 
      "username": "Warren2", 
      "text": "test1" 
     }, 
     { 
      "username": "Warren2", 
      "text": "test2" 
     }, 
     { 
      "username": "Warren2", 
      "text": "test3" 
     }, 
     { 
      "username": "Warren2", 
      "text": "hello" 
     } 
    ] 
] 

我无法解析与jQuery和我认为jQuery是抛出错误,因为对象是一组额外的括号内。我使用的创建对象的数组的代码如下:

// chat history 
var history = []; 

// when the client emits 'sendchat', this listens and executes 
socket.on('sendchat', function (data) { 
    // we tell the client to execute 'updatechat' with 2 parameters 
    io.sockets.emit('updatechat', socket.username, data); 
    // we add the message to the chat history 
    var obj = {username:socket.username,text:data}; 
    history.push(obj); 
    history = history.slice(-100); 
}); 

上午我做错了什么或有什么方法去除多余的一套支架或用jQuery解析呢?当我登录历史数据的node.js被发送给浏览器,它看起来像这样的控制台:

[Object { username="Warren2", text="test1"}, Object { username="Warren2", text="test2"}, Object { username="Warren2", text="test3"}, Object { username="Warren2", text="hello"}, Object { username="Warren", text="test"}, Object { username="Warren", text="test again"}, Object { username="Warren", text="test"}, Object { username="Warren", text="Hey"}] 
+0

如果我从历史记录[0]中删除[0],它仍然有效,但仍有双括号。如果我离开[0],我得到以下错误: historySlice = history [0] .slice(-100); TypeError:Object# has no method'slice' – 0xDECAFBAD 2012-07-05 16:05:54

回答

1
$.each(data, function(index,el) { 
    // el = object in array 
    // access attributes: el.Id, el.Name, etc 
}); 

在另一个计算器后发现了它。有没有看到这之前,但解析传入的数据后使用

var json = $.parseJSON(data); 

上述代码工作完美。