Javascript:将对象推送到集合中

时间:2013-06-21 05:31:15

标签: javascript

我有一个Msg对象和一个MsgCollection对象。

消息对象:

function Msg(text, timestamp, source, thread_id) {
    Msg.RECEIVED = 1;
    Msg.SENT = 2;

    this.thread_id = thread_id;
    this.text = text;
    this.timestamp = timestamp;
    this.source = source;
}

MsgCollection对象:

function MsgCollection() {
    this.all = [];
}
MsgCollection.prototype.push = function(msg) {
    this.all.push(msg);
    console.log("first message text: " + this.all[0].text);
}

在下面的代码中,我获取结果对象并将所有数据放入临时Msg对象,然后将其推送到MsgCollection

var msgColl = new MsgCollection();
for (var i = 0; i < result.texts.length; i++) {
    var tempMsg = new Msg;
    tempMsg.thread_id = result.texts[i].thread_id;
    tempMsg.text = result.texts[i].message;
    tempMsg.timestamp =  Number(result.texts[i].time_received);
    tempMsg.source = result.texts[i].type;

    msgColl.push(tempMsg);
}

不幸的是,当我尝试在push方法中打印this.all[0].text时,似乎停止了执行。换句话说,似乎没有任何东西被推入msgCollection对象。也许这有点复杂,但也许我可以获得一些关于如何调试的指导?

由于

2 个答案:

答案 0 :(得分:3)

var tempMsg = new Msg(); 

tempMsg.timestamp = new Number(result.texts[i].time_received);  

效果很好 DEMO

答案 1 :(得分:0)

请尝试以下代码:

for (var i = 0; i < result.texts.length; i++) {
    var tempMsg = new Msg();
    tempMsg.thread_id = result.texts[i].thread_id;
    tempMsg.text = result.texts[i].message;
    tempMsg.timestamp = new Number(result.texts[i].time_received);
    tempMsg.source = result.texts[i].type;

    msgColl.push(tempMsg);
}

当您要求“如何调试指导”时,您可以随时选择Chrome开发人员的工具,我建议您使用firebug

为简化调试,您也可以执行以下操作(您可以使用try-catch):

try {
   //Your code goes here..
   alert(Obj); //You can Inspect an object here..
}
catch(e) {
    //If any error you will inspect here..
    alert(e); 
}

我认为这可以帮助你......