JavaScript (Array)

Introduction of Array
Array is a collection those values which are related with same data type, suppose we want to insert marks for XII class students, total 50 students are available and every student contain marks for five subjects, so we have to declare (50x5 = 250) variables that need several lines code but by using of array we can create this program by just one line statement "var a=new Array (250)"

Example
var a=new Array(40);

In the above statement “var” is a keyword that is used to declare a variable, and "new Array" is used to declare an array in JavaScript and.



Features of array
1.   Array is an example of static data type and static memory should be allocated before run time therefore it causes of overflow and underflow errors.

2.   In array all elements store in one variable by help of different index numbers and index number should be always starting with zero.

var a=new Array(5);
a[0]=45
a[1]=50
a[2]=67
a[3]=60
a[4]=75

3.   All the elements of array should be related with their one data type.

<html>
<title> Enter marks of five subjects </title>
<body>
<form>
<input type="button" value="Enter marks" onclick="msg()">
</form>

<script>
function msg()
{
var a=new Array(15,7,19,10,25);
for(var i=0; i<5; i++)
{
         document.write("<br>",a[i]);
}
}
</script>

</body>
</html>

Program to find largest value in array
<html>
<title> Program to find largest value in array </title>
<body>
<form>
<input type="button" value="Enter marks" onclick="marks()">
</form>

<script>
function marks()
{
var i,L=0, m=new Array(3);

for(i=0;i<5; i++)
{
m[i]=prompt("Enter marks:");
}

for(i=0;i<5; i++)
{
document.write("<br>",m[i]);
}

for(i=0; i<5; i++)
{
if(L < m[i])
{
L=m[i]; 
}}

document.write("<br>Largest value is: ",L);
}
</script>

</body>
</html>  

No comments:

Post a Comment