Object Collections
Students put many objects into an array and use a loop to make every object act.
Collections of objects
Put objects in an array and you get a kennel full of robot pets — one variable, many critters. Then a loop can visit every pet and ask for its status, no matter how many you adopt.
-
1
An array of objects
Each slot of
petsholds a whole RobotPet object — name, energy, methods and all.pets[0]is Pixel;pets[1]is the next pet. -
2
Loop + method = roll call
foreach pet, callpet.status()— the loop walks the kennel and every pet announces itself. Three pets or three hundred: same three lines of code. -
3
Try it
Adopt a fourth pet with a silly name and run the roll call again. Notice you didn't change the loop at all — that's why collections + loops run every game's enemy list.
Loop through objects.
class RobotPet {
constructor(name, energy) {
this.name = name;
this.energy = energy;
}
status() {
say(this.name + " has " + this.energy + " energy.");
}
}
let pets = [
new RobotPet("Pixel", 3),
new RobotPet("Bolt", 5),
new RobotPet("Zara", 4)
];
for (let pet of pets) {
pet.status();
}
Program result
- Run your code to see output.
Type real JavaScript, then run it.
You stored objects in an array and used a loop to call a method on each one.
Open Collection Builder