Let’s talk about manipulating arrays now. There are a ton of methods for manipulating arrays, but we’ll talk about the mostly used ones.
Before I move on, let me give you the technical terms for an array. The position or spot of an array is considered the index. The values in an array are items or elements. That’s all you’ll need to know!
Converting An Array To A String
If you would like to convert an array to a string, then there’s a very simple method to do so. Clear your script and add this bit of code.
var colors = new Array( "Blue", "Red", "Green" );
var allColors = colors.join();
document.write( allColors + '<br/>' );
First, you create an array filled with colors. Then, we create a variable that will store the string of the array. The method join() does all the work and converts an array to a string for you. Lastly, we output the result into the document.
Deleting The Last Item In An Array
To delete the last item in an array, you simply use the pop() method. Add this bit of code into your script.
document.write( colors + '<br>' );
Adding Elements and Reversing An Array
To add an element, you use the push() method. Like so
colors.push( 'Green', 'Ornange' );
This is the more efficient way to add elements into your array. As it’ll automatically detect the last index for you. You can add as many elements as you want. To separate each element, you use a comma.
To reverse an array, you use the reverse() method. This will automatically switch your array upside down. Add this line of code to do it.
Let’s output this. We’re going to convert this into a string again, but we’re going to separate each element with a hyphen instead of a comma. Add this bit of code into your script.
var allColors2 = colors.join( ' - ' );
document.write( allColors2 );
Like last time, we’re storing the string into a variable. We use the join() method, except we pass in a string. The string you pass in will be the separator between each element. Lastly, we output this.
If you visit your document, then you should get something like this.
Orange – Green – Red – Blue
There are a lot of methods to manipulate your array. Some you’ll use some more than others. I suggest you take the time practice each one and save the link to the documentation on it. To learn more about the Array object, then go here.