2016-07-21 184 views
0

我定義的:動態項目添加到JavaScript對象

var data ={}; 

我想服用點這樣的對象中的每個「行」:

{field1: "bananas", field2:'test', field3:111, field4:"23.4", field5:"bob"}, 
{field1: "fruit", field2:'test again', field3:222, field4:"30", field5:"john"} 

我知道我能做到這一點,以添加動態和靜態數據:

data['field1']= docType; 
    data['field2'] = docRef; 
    data['field3'] = "test3"; 
    data['field4'] = mydynamicdata; 
    data['field5'] = "test5"; 

但是我怎樣才能添加不同的物品線?此代碼只會添加一個項目集,對吧?我如何添加第二個?

謝謝!

+0

您需要一個對象數組 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array –

回答

2

你需要的對象數組 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

var data = []; 

data.push({field1: "bananas", field2:'test', field3:111, field4:"23.4", field5:"bob"}) 
data.push({field1: "fruit", field2:'test again', field3:222, field4:"30", field5:"john"}) 

然後你就可以做出這樣的改變:

data[0]['field1'] = 'new value' 
//or: 
data[0].field1 = 'new value' 

哪裏0是名單內的項目的索引。所以將是第二個對象,依此類推......

+0

你好,這個數據是傳給yui的數據表。它可以接收該對象的數組嗎?現在我傳遞一個數據= {}; – user3643038

+0

實際上,根據文檔 - http://yuilibrary.com/yui/docs/datatable/ - 數據的預期格式是一個數組 –