Arrays In Java Script

If we require many variables of  same or different types then a problem of remembering names of variables and many functional  problems will arise. Concept of array allows us to store different data type  data pieces under the same name in an ordered way. It helps  in creating many variables. There is no need of  remembering their names because they all have the same name but different positions in  the array. The count of location in an array starts from 0 not from 1, means  the first location is 0th location and 12th is 11th .
 
Declaring an array variable
 
Method 1
var d = new Array (“One”, “Two”, “Three”, “Four”);
 
Understanding the declaration
 
var – is reserve word
 
d – is the name of the array
 
new  – is a reserve word  , sets that much number of locations in memory as much parameters given with Array( );
 
Array( ) – is a reserve word , provides the input to new that how much memory locations are to be reserved.
 
“One”, “Two”, “Three”,” Four” – are the values to set in d named array variable as much the count of these variables is that much of locations in memory will be reserved by new (reserve word).
 
 
Method 2
var sales = new Array (12);
 
Understanding the declaration
 
var – is reserve word
 
sales – is the name of the array
 
new – is a reserve word , sets that much number of locations in memory as much parameters given with Array( ), in this case 12 locations will be occupied;
 
Array( ) – is a reserve word , provides the input to new that how much memory locations are to be reserved. 12 – is the count of locations to be reserved.
 
 
Assigning values to an array locations
 
Sales[0] = “Rubber”;
 
Sales [1] = 12000;
 
Sales[2] = “Plastic”;
 
Sales [3] = 18000;
 
At 0th position of sales named array the value is “Rubber “ and at 1st position 12000 is stored. So we can place different data types data in the same array.
 
Example 1
 
<html>
<head>
</head>
<body>
<script type=”text/JavaScript”>
var d = new Array(“One”,”Two”,”Three”,”Four”);
document.write(“Value at 0th position of d is “+d[0]);
document.write(“<br>Value at 1st position of d is “+d[1]);
document.write(“<br>Value at 2nd position of d is “+d[2]);
document.write(“<br>Value at 3rd position of d is “+d[3]);
</script >
</body>
</html>
 
Output is
Value at 0th position of d is One
Value at 1st position of d is Two
Value at 2nd position of d is Three
Value at 3rd position of d is Four
 
 
Example 2
 
<html>
<head>
</head>
<body>
<script type=”text/javascript”>
var sales = new Array(12);
sales[0]=”Rubber”;
sales[1]=12000;
sales[2]=”Plastic”
sales[3]=18000;
document.write(“Value at 0th position of sales is “+sales[0]);
document.write(“<br>Value at 1st position of sales is “+sales[1]);
</script >
</body>
</html>
 
Output is
Value at 0th position of sales is Rubber
Value at 1st position of sales is 12000
Scroll to Top