JavaScript Arrays
When working with complex data, often you will want to store a series of variables. Consider this example:
var s1 = true, s2 = false, s3 = false,
s4 = false;
for (i=1;i<=4;i++) {
// How do we access each s(i) ?
}
In this example, we have four "s(number)" variables. We want to access each of them based on our for loop iteration variable, i. Now, there is a highly technical approach (it's eval("s"+i), which we will explore later), what if we need to create s5, and s6, and s7? Clearly creating new variables for each is impractical. Therefore, we can use an array.
Consider this example:
var s = Array();
s[1] = true;
s[2] = false;
s[3] = false;
s[4] = false;
for (i=1;i<=4;i++) {
alert(s[i]);
}
To create an array, we use the Array() function. Although this is entirely optional, it is recommended when developing complex applications.
An array is a variable of variables. An array has elements, each of which is typically identified by a whole number. When we work with arrays, we treat it as any variable except that we access a particular element like this:
variablename[elementnumber]
The element number, or index, is placed after the variable name in square brackets - [ and ]. The element number can be an actual number, or it can be another variable.
| « JavaScript Switch Statement | JavaScript Objects » |
More JavaScript Tutorials:
» Writing Classes in Javascript
» How To Hide a Frame With JavaScript
» Automatically Inserting the Current URL Into Forms
» Displaying Alternate Page Area in an IFRAME
» Building a Javascript Array
» JavaScript Double Click Trapper


