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.
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
Copy and paste the below code in notepad and save as index.html .Then open with the browser.
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>
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>
0 comments :
Post a Comment