![]() |
![]() |
Javascript Arrays |
Arrays are used to store lists of data for easier access. They can be very useful for sorting data, and retrieving large amounts of input from the user. Here are a few important properties of Arrays in JavaScript
For those with experience programming in other languages, Arrays in JavaScript can be a bit confusing, as they are much more flexible than in languages such as C, or Java.
There are two main ways of creating an array in JavaScript. The first is with what is called an initializer list - a series of values enclosed in square brackets, to tell JavaScript that you want that set of values to represent an array. Here are a few example arrays being created with an initializer list:
In the third example here, we have an array which contains two other arrays - elements 0, 3, and 5 are numbers, element 1 is a string, element 2 is the contents of the variable theAry1 (which is an array), and element 4 is another array created with it's own initializer list. (Note that the length of this array is 6, despite more elements being inside of the sub-arrays. Also, since we have to start counting at 0, the index of the last element is actually 5.)
The second method initializes the array as a JavaScript Object, and specifies it's length. (Objects will be discussed in more depth later.) When the array is initialized this way, it has an initial length, but there is nothing in it. (ie: All of it's elements are undefined.)
Of course, it is possible to use this method to create an array with it's contents already specified, but this is bulky, and more work than just using the initializer list from above, which it functions in a manner identical to:
To refer to an element in an array, you type the name of the array, and then the element's number, in square brackets, like this:
The number inside of the square brackets is referred to as the index for the array. One important thing to note about the numbers used for the indexes of elements in arrays is that the first one is always zero. That means that the first element in theAry1 as it was set above, would be theAry1[0], and the last would be theAry1[4]. (theAry1 has 5 elements, numbered 0,1,2,3,4.)
Since JavaScript treats arrays as Objects, there are some useful properties and methods defined on them. (A property is a variable attached to an object that can tell you useful information about the Object, and a method is a function designed to operate on the data the Object is holding.) - one of those is the .length property, which will tell you how many elements are in an array. For example, theAry1 from above has 5 elements, and the property theAry1.length will return a 5. Remember, there are 5 elements, but the last one is referred to as theAry1[4], because the counting starts at zero. Thus, if we were making a for loop to fill up the contents of thatAry, which we created with the constructor, it would look like this:
It is very important to note however, that arrays can be stretched - this means that if you place a value in an element that does not currently exist, the array will be stretched out to catch that element, creating all of the elements between the current end of the array, and the element you have placed. This can be very useful in some situations, however in others it can be dangerous. For example, in the previous example, if we were to accidentally use <= instead of <, we would create a situation called an infinite loop. Changing the above code to:
The only difference is a single =, however the result is significant. The two pieces of code would run identically up to the moment that element 4 was placed, the difference would come into play - after the loop contents are run, the program returns to the top of the loop and runs the increment, in this case i++, which changes the variable i to 5 - the length of thatAry is five, and in the first case, since 5 < 5 is false, the loop exits. In the second version however, 5 <= 5 is true, so the contents of the loop will run one more time, and place "Hello" into thatAry[5], which until this moment did not exist. Because the array will stretch to include new additions, placing something in thatAry[5] will stretch the array out to include it, causing thatAry.length to now be 6. The loop content finishes, and returns to the top, and the increment, i++ is run, changing i to 6, and the condition is tested once more. Since 6 <= 6 is true, the loop will run once again, stretching the array to 7 elements, then 8, and so on, until the computer runs out of memory available for Javascript to use, at which point the program will crash. In very old browsers (for example Netscape on Windows 3.1) this could actually crash the entire computer due to poor memory management.
Since in JavaScript, unlike in many other programming languages, the length of an array can change after it has been created, there are many useful things that can be done. When entering or creating an arbitrarily long list of values, a single element array is all that needs to be created, and the program can then simply add elements to the array as needed, until all of the relevant data has been stored. You should be aware however, that if you stretch an array more than just a single space at a time (for example, adding element 9 to a 3 element array), all of the elements that should exist between the old end of the array and your new element will also be created, and their values will be set to undefined.
Here is an example program which demonstrates all of the above, plus what happens if you convert an array into a string. Remember that if you add any two variables together, and either of them is not a number, the + will convert both of them into strings, and concatenate the result. Regardless of what they may contain, an Array is not a number, in the same way that a city bus is not a person, despite containing people.
In the last part, the array is printed out as a string - the way JavaScript does this is by converting each element in the array into a string, then printing them out in order, with commas "," between each element. There is no comma placed at the end however, so if something else is appended to the end of the string, it will simply be added on afterwards. Also note that you can't use addition to join two arrays to eachother - they will end up being converted into strings instead, like this
This produces a string which reads as follows:
Note that there is no , between the 5 from the end of theAr1 and the 9 from the beginning of theAr2 - this is because when the arrays are converted to strings, the comas are only placed between the existing elements, not outside of them.
To add two arrays together, you should write a simple for loop, like this:
Since accessing an element outside of the already existing array will just stretch the array, you can add a new element on to the end of theAr1 by just using theAr1.length as the index of the element to be added. The code above will thus go from the start to the end of theAr2, and append each of those elements to the end of theAr1.
Arrays can be very useful for providing dynamic content, when you want to select one possible output from a variety of alternatives. This is a simple example of such a program, which uses an array inside of a function to provide a list of sayings.
Note that since the array was created inside of the function, as soon as the function exits, the array is deleted, and has to be created again from scratch the next time someone runs the function. Since the list of sayings in the array is re-created from scratch every time the function runs, the list of sayings can not be altered. To make the list available to be altered, you can change it to be a global variable, which can then be accessed and modified by any number of functions, like in this example, where we not only read items from the array, but also add things to it for later use:
In the previous example, another feature of the Array object in JavaScript was used - the join() method - this is a function which takes the contents of the array, and converts it into a string, with the parameter for the join function as a separator between parts. In the example above, "\n" was used, which is an escape sequence that means "Add a new line".
The variable you put an array into doesn't actually hold the whole array. It actually holds what is called a 'pointer' - a sign which points to the place in memory where the array sits. This is important because when you are passing an array as a function parameter, you are not making a copy of the array like you do with numbers and strings, but a copy of the pointer - what it points to is the same place, so if you change your array in the function, it changes the real array!
Here is a version of the previous program altered so that it takes the array as a function parameter. If you look at the onclick attributes for the form buttons, you'll see that the name of the array is now being passed in. This allows us to add even more features to our page, without making our programs that different - except for having the name of a parameter in the brackets at the start, our function definitions are exactly the same as before. The difference here, is that we can now use more than one array, and the same functions can deal equally with any of them:
In this example, we've shown a new method on the Array object - join(). Normally, when an array is converted into a string (for example, by using addition to concatenate it to another variable as a string) it will place comas between the elements of the array. By using the join() method, we can decide for ourselves what we want the separator between the elements of the array to be. For example, if we wanted to print out the contents of an array as a row in a table, we could do this:
The above would output HTML code to look like this:
On occasion, you may want to store tables of data, such as a list of information about a group of people, or the positions of pieces on a chess board. Rather than creating a separate array for each row, you can in fact hold all of the information under one heading, by making an array of arrays, which is referred to as a multi-dimensional array. Essentially, it is a single array, whose elements are all also arrays. To create a multidimensional array, you should first create the base array, and then initialize each element separately as another array, like this:
Then, you can refer to the elements in the nested array by using two subscripts, like this: nested[1][4] - here is a simple program which creates a multi-dimensional array, and stores the numbers from 0 to 8 in it.