javascript arrays | javascript array methods

Before we even jump on to javascript Array methods we need to first understand what is an Array and why we need javascript arrays.

Array

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

Object way

var student=new Array();
student[0]="suresh";      
student[1]="kumar";
student[2]="jain";

Lets optimize it further

var student=new Array("suresh","kumar","jain");

Literal way of declaring an array or creating an array

var student=["suresh","kumar","jain"];

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[2]); //kumar  
//set an array value
studentArr[2] = "changed to sureshkumar"; 
console.log(studentArr[2]);//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

suri

I Am suresh(suresh kumar )a Web developer,Freelancer,webdesigner,UI developer from bangalore. Got 6+ yrs of IT experience . I specialize in standards-based XHTML, CSS and JavaScript web development. Each site I develop is built to be search engine friendly (SEO), using the latest development principles and techniques.

You may also like...

Add Comment Register



Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>