2013-06-21 55 views
1

我有一個Msg對象和一個MsgCollection對象。Javascript:將對象推入集合

消息對象:

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); 
} 

在下面的代碼,我把結果對象,並把所有的數據到臨時消息對象時,它推到一個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); 
} 

不幸的是,似乎執行我當我嘗試在推送方法中打印出this.all[0].text時,s停止。換句話說,似乎沒有任何東西被推入msgCollection對象。也許這有點複雜,但也許我可以收到一些關於如何調試的指導?

感謝

+0

是什麼在控制檯說,當你輸出'this.all [0]'? –

+0

'var tempMsg = new Msg();' – Ilya

+1

@Ilya:沒有區別afaik ... – elclanrs

回答

3
var tempMsg = new Msg(); 

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

效果很好
DEMO

+0

你是對的,一切似乎都奏效。我的代碼中的其他內容正在搞亂。不管怎麼說,還是要謝謝你。 – adrianmc

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); 
} 

正如你所要求的'如何調試的指導',你可以隨時選擇鉻開發者的工具,否則我建議去用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); 
} 

,我認爲這可以幫助你..