JAVASCRIPT ARRAY
Array is a collection those values which are related with same data type, suppose we want to insert marks for XII class students and total 50 students are available and every student contain marks for five subjects, so we have to declare (50 x 5 = 250) variables that need several lines code but by using of array we can create this program by just one line statement (var m[250]).
JAVASCRIPT ARRAY EXAMPLE
var a=new Array[40];
In the above statement “var” is a reserved JavaScript keyword, that is used to create a variable and “a” is array name and [40] is size of array.
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 unique index number and first value of array always store in zero (0) index number.
3. All the elements of array should be related with their one data type.
HOW TO DECLARE ARRAY IN JAVASCRIPT
In JavaScript "Array" keyword is used to declare an array, as in below example the array "m" contain the five values.
var m=new Array(4,7,12,9,8);
As we know, that array stores its value by help of unique index number.
m[0] = 4
m[1] = 7
m[2] = 5
m[3] = 9
m[4] = 8
JavaScript Program To Declare And Print Array's Values
JavaScript Program To Declare And Print Array's Values
<html>
<title> Array example in JavaScript </title>
</html>
<script>
var m=new Array(4,7,12,9,8);
for(i=0; i<5; i++)
{
document.write(m[i],"<br>");
}
</script>
<title> Array example in JavaScript </title>
</html>
<script>
var m=new Array(4,7,12,9,8);
for(i=0; i<5; i++)
{
document.write(m[i],"<br>");
}
</script>
JAVASCRIPT PROMPT BAR
The prompt bar is used to accept any input from an user at run time.
For example in the below program variable "a" store value from prompt bar and printing it, by help of document.write function.
<script>
var a=prompt("Enter your age:");
document.write("Your age is :",a);
</script>
Program Store Array's Value At Run Time
<html>
<title> Store values in array at run time </title>
</html>
<script>
var m=new Array(5);
for(i=0; i<5; i++)
{
m[i]=prompt("Enter values in array:");
document.write(m[i],"<br>");
}
</script>
Program To Calculate Sum of Array Values
<html>
<title> Program to calculate sum of array values </title>
</html>
<body>
<form>
<input type="button" value="Enter Marks" onClick="marks()">
</form>
</body>
<script>
function marks()
{
var i,sum=0;
var m=new Array(5);
// Loop to enter values in array
for(i=0; i<5; i++)
{
m[i]=prompt("Enter values in array:");
}
//Loop to print array value and calculate sum
for(i=0; i<5; i++)
{
document.write(m[i],"<br>");
sum=sum+Number(m[i]);
}
document.write("<br>Total is: ",sum);
}
</script>
0 Comments