Adding an item to the end of an array
In javaScript we can add an item in the end of array by following method which means the new item will get place in the end of array.
We can add new item in array end with the following method. Suppose we have 2 items in this array example
[code lang=”js”]
var border =[‘1px’,’solid’]
[/code]
to add a third item to the end of an array we simply put the index value in the brakits with the addition of 1
[code lang=”js”]
name of var [ number of items present in an array + 1 ]=’new item’;
so we can write it as
border [3]=’Grey’;
it would add a new item at third spot in the array like this
[‘1px’,’solid’,’Grey’]
[/code]
items can be added by other methods describing below:
Adding an item to the beginning of an array
To add new item in the biginning of array we use the following method in javaScript to add new item in start of array which will take 0 index place and the previous 0 index element would be moved to 1 index.
suppose we have 2 items in this array example
[code lang=”js”]
var border =[‘solid’,’Grey’]
To add an item to the beginning of an array simply use "unshift()" command
for example
name of var.unshift(‘new Item’);
so we can write this command as
border.unshift(‘1px’);
above unshift command would give this result
[‘1px’,’solid’,’Grey’]
[/code]
Choosing where to add items to an array
Similarly we can add items by push() command push is a javaScript default built in function which can help us to push an item in array where ever we want. We can tell javaScript where to add new element in array using push method.
[code lang=”js”]
suppose we have an array variable
var headings = [h1,h2,h3]
to add two or three more items
headings.push(h4,h5,h6);
result would be as
[h1,h2,h3,h4,h5,h6]
[/code]
it will add three more items or so on in the end of an array
“.length property” to add an item to an array
[code lang=”js”]
lets we have a variable
var h = [1,2,3,4]
to add another integer or string value we will use length property as
h[h.length]=5
After code run add one value i.e "5" to the end of an array Gives the result as
[1,2,3,4,5]
[/code]
Deleting elements from an array JavaScript.
To delete items from array in javaSCript we have to know which one is to delete and we can use two methods to delete elements from array one is pop method and second is shift method. Lets suppose we have a variable
[code lang=”js”]
var h = [1,2,3,4]
we can delete last digit or value in an array by putting "pop()" or "shift()" functions as below
h.pop() or h.shift()
this code run will remove last item from array gives the same result as
[1,2,3]
now array has 3 items
[/code]