In javascript we have array with static number of objects.
objectArray = [{}, {}, {}];
Can someone please explain to me how can I make this number dynamical?
asked Apr 14, 2012 at 12:20
SakerONE
1391 gold badge3 silver badges10 bronze badges
-
add a dynamic amount of indexes. I'm not really sure what you're asking.thescientist– thescientist2012年04月14日 12:23:32 +00:00Commented Apr 14, 2012 at 12:23
-
Why don't you read some documentation? developer.mozilla.org/en/JavaScript/Guide/…Felix Kling– Felix Kling2012年04月14日 12:42:49 +00:00Commented Apr 14, 2012 at 12:42
-
I read, but another, thank you for this one)SakerONE– SakerONE2012年04月14日 12:48:41 +00:00Commented Apr 14, 2012 at 12:48
2 Answers 2
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!";
answered Apr 14, 2012 at 12:23
Michael Berkowski
271k47 gold badges452 silver badges395 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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";
answered Apr 14, 2012 at 12:24
frostmatthew
3,2964 gold badges44 silver badges53 bronze badges
Comments
lang-js