admin管理员组

文章数量:1327083

In javascript we have array with static number of objects.

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

Can someone please explain to me how can I make this number dynamical?

                                                                   

                                      

                                      

In javascript we have array with static number of objects.

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

Can someone please explain to me how can I make this number dynamical?

                                                                   

                                      

                                      

Share Improve this question edited Apr 14, 2012 at 12:40 SakerONE asked Apr 14, 2012 at 12:20 SakerONESakerONE 1391 gold badge3 silver badges10 bronze badges 3
  • add a dynamic amount of indexes. I'm not really sure what you're asking. – thescientist Commented Apr 14, 2012 at 12:23
  • Why don't you read some documentation? developer.mozilla/en/JavaScript/Guide/… – Felix Kling Commented Apr 14, 2012 at 12:42
  • I read, but another, thank you for this one) – SakerONE Commented Apr 14, 2012 at 12:48
Add a ment  | 

2 Answers 2

Reset to default 7

You don't have to make it dynamic, it already is. You merely need to add more objects onto the array:

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

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

In JavaScript, array lengths need not be declared. They're always dynamic.

You can modify the individual objects by array key:

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

You don't need to specify an array size when first creating the array if you don't want to. You can use:

var objectArray=new Array();

to create the array and add elements by:

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

本文标签: javascriptDynamic object arrayStack Overflow