Object Arrays

Resources:

Shiffman - 7.3: Arrays of Objects - p5.js

Arrays of Objects

We can think of objects as our fundamental building block for creating any custom entity within our code. Arrays are used to store and organize collections. Putting the two together gives us the ability to fully utilize the modularity and repeatabiltiy of object-oriented programming. An animation of snowflakes, a group of sound bytes, or a collection of asteroids in the classic arcade game are containers of custom entities, which we would represent as a arrays of objects.

This example makes an array containing a single Spot. Try to edit it to create more Spots with different parameters.

The previous method is fine for a couple Spots, but what if we need hundreds? We'd probably want to automate creating and operating on that large of an array using iteration, like a for() loop.

Solution

Push and Pop

The push() method adds a new element to an array (at the end):

let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits

The pop() method removes the last element from an array:

let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.pop(); // Removes the last element ("Mango") from fruits

This example shows an interactive example with a different class, called Ring, using push() to add new elements to the ring array.