Sunday, December 9, 2007

Working with arrays

Working with arrays

One important programming technique is the use of arrays. Most programming language support them in a certain manner. Maybe you have already come to a point where arrays would help you further. But if you looked through the documentation provided by Netscape you realized that nothing is said about arrays. The problem is that arrays do not exist in JavaScript! But I can show you a work around of course!

First, what are arrays? You could say that arrays are many variables bound together. Let's say that you want 10 variables. You could begin with the variables a, b, c ... But this is really complicated. Especially if you want to store 100 or more variables. If you have an array which is called 'MyArray' and it has got 10 elements, you could address the different elements with MyArray[1], MyArray[2], MyArray[3]... (many programming languages start with the 0 as the first element- but we want to have the 1 as first element because this is the way we use it later in JavaScript). So if you want to keep the number 17 in the first element you have to write MyArray[1]=17. You see that you can work with arrays the same way as with normal variables. But there are some more features. If you want to store the number 17 in every element you can write it this way:

for (var i=1;i<11;i++)>

The for- command tells the computer how often the next command is going to be executed. The for- loop starts with i= 1. First the computer gets the command MyArray[1]= 17. After this i is incremented by 1 and then the command is MyArray[2]= 17. i is incremented until it has the value 10. (The expression i<11>

Now I will show you a function to initialize arrays. This function was discussed in the JavaScript Mailing list.

function initArray() {

this.length = initArray.arguments.length

for (var i = 0; i <>

this[i+1] = initArray.arguments[i]

}

You don't need to understand this function. You only have to know how to use this function. If you want to create an array with three elements you just write: var MyArray= new initArray(17,18,19). 17,18,19 are assigned to the elements 1,2,3. You could as well write strings to your array. So you don't have to matter which type is used! var heyho= new initArray("This","is","cool"). Mixing different types is no problem at all: var Mixedup= new initArray(17,"yo",103).

Here is the output of the following code:

Element No. 1: 17

Element No. 2: yo

Element No. 3: 103

This is the script for the output:

No comments: