Code Snipets

Javascript – Array operations

Posted in JavaScript by mauliksoni on March 11, 2010

Creating an Array

var days  = [‘Mon’,’Tue’,’Wed’,’Thur’,’Fri’,’Sat’,’Sun’];
alert(days[0]);

Adding an item at the end of an Array

var properties = [‘red’,’14px’,’Arial’];
properties[3] = ‘bold’;
// or
properties[properties.length]=’bold’;
// or
properties.push(‘bold’);

Adding an item at the beginning of an Array

Properties.unshift(‘bold’);

Deleting an item from an Array

var p=[0,1,2,3]
var removedItem = p.pop();

POP() -removes the last item from the array.
SHIFT() -removes the first item from the array

Adding and Deleting with splice()

var fruit = [‘apple’,’pear’,’kiwi’,’orange’];
fruit.splice(1,2);
// removes pear and kiwi from array

Adding item with splice()

var fruit = [‘apple’,’pear’,’kiwi’,’orange’];
fruit.splice(2,0,’grapes’,’banana’);
//2 is the index where new item will be inserted, and 0 means you do not want to delete any items.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.