If you have a list of shapes, for example, you can use the following line of code as a declaration of your array:
var shapes = [“Triangle”,”Rectangle”,”Circle”];
Of course, you can also use multiple lines:
var shapes = [
The real benefit of arrays and data structures become clear when you start handling larger amounts of data. For example, an array would come in handy if you wanted to store 100 different shapes.
You can always access the value of a certain array element by using its index. For example, if you want to assign the value “Circle” to variable x, you would do the following:
var x = shapes;
Remember that we start counting spots in an array at zero. In other words, the first slot in our example array is:
You can also change the value of any spot inside the array using the index:
shapes = “Square”;
New is the keyword we use to create an object like an array and populate it with values:
var shapes = new array("Triangle", "Rectangle", "Circle");
The following example describes a car array with some of the car’s specs:
var car = [“Volvo”, “Red”, 1999];
This array holds integer and string variable types and we can access each spot inside the array using its index. In other words, car returns 1999. You can have many different object types together inside the same array, even functions.
You can use the method called “push” to add a new element to an array. For example, the method
will add “Square” to the end of the shapes array. Its length will now be four. Got it? There is much more to come! Start your learning journey now with RoboGarden. Register for free.