How to add and remove first item in an array using javascript array method?

Hi friends in this post I am sharing about adding and removing array items from first using javascript array method.We have already shared how to remove array items from last . Also shared how to remove particular array item using array length property. Here we are using unshift to add and shift to temove array items at first.




How to add an item in array first using javascript array method?

We have used unshift in the below code and it was mentioned in yellow highlighted color.Output was given in animated demo.
Copy and paste the below code in notepad and save as index.html .Then open with the browser.
Note: Sometimes unshift will not work in older version browsers.And it shows the output as undefined

<button onclick="functiontoaddelement()">Click here to add
Array Elements
From First For Each Click</button>
<p id="abc"></p>
<script>
var books=['english' , 'science','maths'];
document.getElementById("abc").innerHTML = books;
function functiontoaddelement() {
    books.unshift("Geography");
    document.getElementById("abc").innerHTML =books;
}
</script>

unshift-javascript

How to remove an item in array first using javascript array method?

We have used shift in the below code and it was mentioned in yellow highlighted color.Output was given in animated demo.
Copy and paste the below code in notepad and save as index.html .Then open with the browser.

<button onclick="functiontoremoveelement()">Click here to
Remove Array Elements
From First OnebyOne For Each Click</button>
<p id="abc"></p>
<script>
var books=['english' , 'science','maths'];
document.getElementById("abc").innerHTML = books;
function functiontoremoveelement() {
books.shift();
document.getElementById("abc").innerHTML =books;
}
</script>
shift-javascript
Print Friendly and PDF
SHARE

About me

Hi. I am interested in blogging.And sometimes play with webdesign,web development,domain sale,designing logo and more.

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment