Showing posts with label javascript Array. Show all posts
Showing posts with label javascript Array. Show all posts

Wednesday, June 8, 2016

Array in Javascript

One of the most important object in javascript is Array object.

The Array in javascript is used to store the multiple value in a single variable.

Syntax:

var arrayVariableName=[item1, item2, item3];

or

var arrayVariableName=new Array(item1, item2,...);

Examples:

1. Assign values in array

var arr=[1,2,3,'a','b',1.5];

2. Add element in array
var arr=[1,2,3,'a','b',1.5];
arr.push("xyz");
console.log(arr);

//Result will be
[1,2,3,'a','b',1.5,'xyz'];

3. Remove Element from array:

var arr=[1,2,3,'a','b',1.5];

i) Remove last item:
arr.pop();

ii) remove the more then one item by:

arr.splice(0,1);// it takes two parameter fromIndex and No of element to remove

Result:
It will change the original array like below:
[2, 3, "a", "b", 1.5]

and return a new array also (list of the element removed) like below:
[1]

It also takes one more parameter to insert items form where item are being removed. 

arr.splice(0,1,'aaa','bbb')

Result:
it will return [1]

and

will modify the original array like below:
["aaa", "bbb", 2, 3, "a", "b", 1.5]