2012-04-14 90 views
2

在JavaScript中我們有靜態數量的對象的數組。動態對象數組

objectArray = [{}, {}, {}]; 

有人請向我解釋我該如何使這個數字動態?

+0

添加索引的動態量。我不確定你在問什麼。 – thescientist 2012-04-14 12:23:32

+0

你爲什麼不讀一些文檔? https://developer.mozilla.org/zh/JavaScript/Guide/Predefined_Core_Objects#Array_Object – 2012-04-14 12:42:49

+0

我看了,但另一個,謝謝你這個) – SakerONE 2012-04-14 12:48:41

回答

7

你不必讓它充滿活力,它已經是。您只需要在陣列中添加更多對象:

// Add some new objects 
objectArray.push({}); 
objectArray.push({}); 
console.log(objectArray.length); // 5 

// Remove the last one 
objectArray.pop(); 
console.log(objectArray.length); // 4 

在JavaScript中,不需要聲明數組長度。他們總是充滿活力。

您可以通過數組鍵修改單個對象:

// Add a property to the second object: 
objectArray[1].newProperty = "a new property value!"; 
+0

非常感謝你) – SakerONE 2012-04-14 12:32:05

0

你並不需要首先創建數組時指定數組的大小,如果你不想。您可以使用:

var objectArray=new Array(); 

創建數組,並添加元素:

objectArray[0] = "something"; 
objectArray[1] = "another thing"; 
objectArray[2] = "and so on";