Saturday, April 30, 2011

JavaScript Arrays - XIX


What is an array?

Arrays are a fundamental part of most programming languages and scripting languages. Arrays are simply an ordered stack of data items with the same data type. Using arrays, you can store multiple values under a single name. Instead of using a separate variable for each item, you can use one array to hold all of them.
For example, say you have three Frequently Asked Questions that you want to store and write to the screen. You could store these in a simple variable like this:
faqQuestion1 = "What is an array?"
faqQuestion2 = "How to create arrays in JavaScript?"
faqQuestion3 = "What are two dimensional arrays?"
This will work fine. But one problem with this approach is that you have to write out each variable name whenever you need to work with it. Also, you can't do stuff like loop through all your variables. That's where arrays come into play. You could put all your questions into one array.

Visualizing Arrays

Arrays can be visualized as a stack of elements.
Array
0What are JavaScript arrays?
1How to create arrays in JavaScript?
2What are two dimensional arrays?
Note: Some languages start arrays at zero, other start at one. JavaScript arrays start at zero.

Creating Arrays in JavaScript

Most languages use similar syntax to create arrays. JavaScript arrays are created by first assigning an array object to a variable name...
var array_name = new Array(number_of_elements)
then by assigning values to the array...
array_name[0] = "Array element"

So, using our prior example, we could write:
var faq = new Array(3)
faq[0] = "What are JavaScript arrays"
faq[1] = "How to create arrays in JavaScript?"
faq[2] = "What are two dimensional arrays?"

Accessing Arrays in JavaScript

You can access an array element by referring to the name of the array and the element's index number.

Displaying Array Elements

document.write(faq[1])
The above code displays the second element of the array named faq (JavaScript array index numbers begin at zero). In this case, the value would be How to create arrays in JavaScript?

Modifying the Contents of an Array

You can modify the contents of an array by specifying a value for a given index number:
faq[1] = "How to modify an array?"
In this case, the value of the second element of this array would now be How to modify an array?

Two Dimensional Arrays

So far we've only discussed one dimensional arrays. You can also create two dimensional arrays, which can be much more powerful than one dimensional arrays. Two dimensional arrays are covered in the next lesson.

No comments:

Post a Comment