2013-02-23 60 views
1

我有下面的代碼,這是行不通的。對象編輯的javascript對象

var conversations = { }; 
conversations['5634576'].name = 'frank'; 

顯然我不能在對象內創建對象。我想使用會話對象來存儲對象數組,以保留客戶端消息的歷史記錄與localStorage以節省空間服務器端。

但很顯然,我甚至不能在對象內部創建變量,除非它們已經存在,就像這樣:

var conversations = { 123: { name: 'test' } }; 
conversations[123].name = "frank"; 

但是,因爲我不知道將要使用的ID,我不知道如何解決這個問題。

任何想法?

+1

'var conversations = {};會話['5634576'] = {};會話['5634576']。name ='frank';',您可以使用if檢查第二步是否必要if(!conversations.hasOwnProperty('5634576')){/*..*/} – 2013-02-23 17:51:13

+0

what a麻煩......好吧,謝謝! – 2013-02-23 17:51:50

+0

或'var conversations = {};對話['5634576'] = {名稱:'坦率'}'。 *「真是太麻煩了。」*:嗯,你期望什麼?您正試圖訪問屬性「5634576」處的值,該值不存在。請閱讀[MDN - 使用對象](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects)。 – 2013-02-23 17:52:00

回答

3

你需要做的是這樣的:

// Create an object 
var conversations = {}; 

// Add a blank object to the object if doesn't already exist 
if (!conversations.hasOwnProperty('5634576')) { 
    conversations['5634576'] = {}; 
} 

// Add data to the child object 
conversations['5634576'].name = 'frank'; 

對象將是這樣的:

conversations{ 
    '5634576': { 
     name : 'frank' 
    } 
} 

更新

你可以,如果該元素存在使用in

檢查 ​​3210
+0

數組呢?如果我像這樣實例化數組 - >'conversations ['5634576']。messages = [];會話['5634576']。messages.push(消息);'我將失去之前的消息。我能阻止這個嗎? – 2013-02-23 17:54:58

+0

'conversations ['5634576'] =對話['5634576'] || {};會話['5634576']。messages = conversations ['5634576']。messages || [];' – 2013-02-23 17:55:30

+0

@john:只有'conversations ['5634576']。messages = [];''.messages'還沒有退出。顯然,當您分配一個新值時,您將丟失以前的任何值。 – 2013-02-23 17:55:39

0

在您的代碼中,您不能將一個變量添加到索引'5634576',因爲它不存在。

var conversations = { }; 
conversations['5634576'].name = 'frank'; 

您需要創建它,然後分配valriable

var conversations = { }; 
conversations['5634576'] = {}; 
conversations.name = 'frank'; 
0

也許最短的方式:

var conversations = {}; 
(conversations['5634576'] = {}).name = 'frank'; 
0
// build this how you were 
conversations = {}; 

// if conversations[12345] is defined, use it: 
// else set it to an object with the desired properties/methods 
conversations["12345"] = conversations["12345"] || { name : "Frank", messages : [] }; 
conversations["12345"].messages.push(new_msg); 

我假設你將成爲在功能,XHR或其他方式下執行此操作

conversations.add_message = function (msg) { 
    var id = msg.conversation_id; 
    conversations[id] = conversations[id] || 
         conversations.new_conversation(msg.user_name); // returning a conversation object 
    conversations[id].messages.push(msg); 
}; 


conversations.new_conversation = function (name) { 
    return { name : name, messages : [], etc : {} }; 
};