You can store a data of any type in a variable that is used in Programming language, in it you cannot store multiple data values, if you want to store multiple data values in a variable, then use the array.
Array data can store multiple data of one type. Array data is a collection of items. Use the array to store multiple data of same type in a variable name. It can store all types of data, in this data indexing. Starts from 0 as [0,1,2, n]
You can create an array with 3 types in javascript.
1 literal
2 using new keyword
3 constructor
All data values in a literal array are written inside square [] brackets separated by comma (,) (separate), in which you can store multiple data of the same type in a variable name.
Syntax
var arrayname = [value1, value2 ..... valueN];
Example 1
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var student=["Vijay","Ajay","sanjay"]; for (i=0;i<student.length;i++){ document.write(student[i] + "<br/>"); } </script> </body> </html> |
Output
Vijay Ajay sanjay |
In this, in parentheses () or small brackets, write all the data values inside double quote ("") separated by comma (,) (separate), the new keyword is used when the constructor array is created.
syntax
var arrayname = new Array ("value1", "value2" ..... "valueN");
example 2
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var i; var student = new Array("Vijay", "Ajay", "Sanjay"); for (i=0;i<student.length;i++){ document.write(student[i] + "<br>"); } </script> </body> </html> |
Output
Vijay Ajay Sanjay |
In this, use the new keyword to create an array, all the data value is stored in a variable name using the index number.
Example 3
<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var i; var student = new Array(); student[0] = "Vijay"; student[1] = "Ajay"; student[2] = "Sanjay"; for (i=0;i<student.length;i++){ document.write(student[i] + "<br>"); } </script> </body> </html> |
Output
Vijay Ajay Sanjay |