Arrays

An array is a type of variable that can hold many 'elements' - many separate variables of the same type. This is useful whenever you want to have a lot of things that work in the same way. If you find yourself creating a lot of variables with similar names and the same type, then think about replacing them with an array.

There are some rules about creating and using arrays. An array has one variable name, but to get access to the individual elements in the array, the name should be followed by a number inside square brackets like this: myArray[3]. Unfortunately, the convention is that array element numbers start with 0, so myArray[0] is the first element and myArray[3] is the fourth element. You can create (declare) an empty array using var myArray = []; To put elements into an array, you can assign values to particular element numbers like this:
myArray[0] = "cat";
or you can add elements to the array using myArray.push("dog");

In the example below, I have created three arrays to hold the x position, the y position and the color of circles to be drawn. In the setup function, I have created the first element of each array. The draw function uses a "for loop" to go through all the elements in the array and draw them on the screen. myArray.length gives the number of elements in the array. At first, only the single element created in the setup function is drawn. However, the "mouseClicked" function creates a new element in all three arrays each time the mouse is clicked. The draw function will always draw all the current elements in the array.

Source code: p5/arrays/sketch.js