Pop() to remove last element of an array

<script type="text/javascript">
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
document.write(scripts.join(" ,"));
document.write("<br>--Now after applying pop()--<br>");
scripts.pop();
document.write(scripts.join(" , "));
</script>
The last element HTML will be removed (and returned )from the array. Output is here.
PHP , ASP , JavaScript , HTML
--Now after applying pop()--
PHP , ASP , JavaScript
We can remove the last element of the array by applying pop() method to the JavaScript function.
last_element=scripts.pop();
This way the array length or size also decreases by one.

This pop() method changes the original array.
It returns the removed element.
Where scripts is our array object.

Getting the last element after removal

<script type="text/javascript">
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";

var str=scripts.pop();
document.write(str); 
</script>
Output is here
HTML

Numeric Keys

The assigned numeric keys are remain same after applying pop()
<script type="text/javascript">
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";

scripts.pop();
for (var key in scripts) {
  document.write("key : " + key + "  =>value: " + scripts[key] + "<br>");
}
</script>
Output is here
key : 0 =>value: PHP
key : 1 =>value: ASP
key : 2 =>value: JavaScript
We can use shift() to remove first element from the array

DEMO of Array Pop Removing all elements of an array
Array Reference How to display elements of an Array

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer