An array is a special variable, which can hold more than one value at a time.
Lets look at an example
If you have a list of items (a list of student names, for example), storing the cars in single variables could look like this:
var student1="suresh"; var student2="kumar"; var student3="jain";
However, what if you want to loop through the students and find a specific one? And what if you had not 3 student, but 100?
The solution is an array!
Creating an Array
var student=new Array(); student="suresh"; student="kumar"; student="jain";
Lets optimize it further
var student=new Array("suresh","kumar","jain");
Literal way of declaring an array or creating an array
How to test an Array object
var student="I am just a string"; var studentArr=['suresh','kumar']; console.log(Array.isArray(student)); // false console.log(Array.isArray(studentArr)); // true
How to get and set array values
//get am array value var studentArr=['suresh','kumar']; console.log(studentArr); //kumar //set an array value studentArr = "changed to sureshkumar"; console.log(studentArr);//suresh kumar
convert array to string
//get am array value var studentArr=['suresh','kumar']; console.log(studentArr); //[suresh,kumar] studentArr.toString(); //suresh,kumar console.log(studentArr);
Concat two arrays
Joins two or more arrays, and returns a copy of the joined arrays
var student1= ["suresh", "kumar"]; var student2= ["rajesh", "kumar", "sharma"]; var student3= ["ramesh"]; var children = student1.concat(student2,student3); //Output:suresh,kumar,rajesh,kumar,sharma,ramesh
indexOf() in arrays
The indexOf() method searches the array for the specified item, and returns its position.
The search will start at the specified position, or at the beginning if no start position is specified, and end the search at the end of the array.
var student= ["suresh", "kumar", "jain"]; var a = fruits.indexOf("kumar"); //returns 1