Think that we have to store five names. To do that we have to define 5 separate variables like below.
var name1 = "John";
var name2 = "Ann";
var name3 = "Nick";
var name4 = "Steve";
var name5 = "Deena";
This is not much difficult, because there are only 5 names. But what would happen if we have to store names of students of a class or a school. Oh...it will be a really mess. Isn't it? Thinkig of storing each student's name in a seperate variable makes us confused. So, what is the solution for this? Solution is Array.
What is an array?
Array is a collection of variables of same type. We can store multiple values in a single variable using an array.
That means all the names of the students' of class or school can be stored in a single variable. Great. Isn't it?
How to create an array?
To declare an array, following syntax is used.
var arrayName = new Array();
We can insert values to array as follows,
var names = new Array("John", "Ann", "Nick", "Steve", "Deena");
In here, the values that stored in the array are called as elements.
To print this array,
document.write(names);
Example 1
Figure 1
In here 5 values are stored in one variable called 'names'. The result we got is below.
Figure 2
As you can see, as the result we got the whole array. If we have to display only one element from the array, what we should do?
For that, we can use array index. Array index is the position of the element inside the array. By using array index, we can access an individual element inside the array.
Example 2
Figure 3
When we working with arrays, computers start working at 0 instead of 1. So the index of first element is 0. So the names[0] is "John" and names[1] is "Ann". The result we got is shown in figure 4.
Figure 4
If we don’t know the elements of array at the beginning and we only know the size of array, how to create an array. For that, first we have to declare the array like this.
var arrayName = new Array(size of array);
eg: var names = new Array(5);
Then we can insert elements into array.
eg : names[0] = "John";
names[1] = "Ann";
Example 3
Figure 5
The result is,
Figure 6
If we don't know the size of the array or elements of the array at the beginning, how to create an array?
To do that we have to declare array first as follows.
var arrayName = new Array();
Then we have to declare elements as follows.
names[0] = "John";names[1] = "Ann";
In here, we declared two variables. So, the array has two variables.
If we declare 3 variables, then array has 3 variables. Like that the length of array is changed and it is not fixed.
We can find the length of array as follows.
arrayname.length
By using this we can find out the number of elements in the array.
Example 4
Figure 7
The result is shown in figure 8.
Figure 8
Hope this tutorial will be helpful to understand arrays of JavaScript.
No comments:
Post a Comment