While they may seem daunting at first, arrays are actually quite easy to use once you get the hang of them. In this blog post, we’ll take a look at what arrays are, how to create them, and how to work with them in your own programs.
What is an Array?
The array literal method looks like this:
var myArray = [ ];
Creating an Array
Creating an array is easy! All you need to do is use the keyword “new” followed by the name of the array’s datatype (in our case, that’s “Array”). For example:
var myArray = new Array();
This will create an empty array that you can then populate with your own data. You can also create an array with data already stored in it by adding a list of values inside parentheses after the datatype name:
var myArray = new Array(1, 2, 3);
This will create an array with three elements: 1, 2, and 3. You can access these elements using their index numbers (more on this later).
Working with Array Data
Once you’ve created an array, there are a variety of ways that you can work with the data inside it. Here are some of the most common operations:
Adding Elements: To add an element to an array, use the “push” method. For example: myArray.push(4); This will add 4 to the end of our array. If we print out our array now, it will look like this: [1, 2, 3, 4]
Removing Elements: To remove an element from an array, use the “pop” method. For example: myArray.pop(); This will remove the last element from our array (in this case 4). If we print out our array now, it will look like this: [1, 2, 3]