Javascript – Array operations

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 comment