push(): Adding elements to an array

<script>
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";

scripts.push("VBScript","Perl");

document.write(scripts.join());
</script>
Output
PHP,ASP,VBScript,Perl
JavaScript arrays We can add new elements at the end of the array by using push() method. This way array length increases. Here is the syntax to add elements to an array.
scripts.push("VBScript","Perl");
scripts is the array to which we added two more elements.

Here is the complete code using join() with line breaks.

<script type="text/javascript">
var scripts = new Array();
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
document.write(scripts.join(" <br> "));
document.write("<br>--Now after applying push()--<br>");
scripts.push("VBScript","Perl");
document.write(scripts.join(" <br> "));
</script>
Output
PHP
ASP
JavaScript
HTML
--Now after applying push()--
PHP
ASP
JavaScript
HTML
VBScript
Perl
Adding elements at the starting of an array by using unshift() method

The above code will add VBScript and Perl at the end of the array and display the full list.

Numeric Keys

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

scripts.push("VBScript","Perl");
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
key : 3 =>value: HTML
key : 4 =>value: VBScript
key : 5 =>value: Perl

add or remove elements at any position of an array by using splice method

Multidimensional array

<script>
var my_ans = new Array(); // declaring array 
my_ans.push({0:45,1:55,2:65});	
my_ans.push({0:145,1:155,2:165});	
my_ans.push({0:245,1:255,2:265});	

// displaying the array data //

for(i=0;i<3;i++){
 document.write("key : " + i + "  =>value: " + my_ans[i][0] +
 ',' +my_ans[i][1] + ',' +my_ans[i][2] + "<br>");
}
	
</script>
Output is here
key : 0 =>value: 45,55,65
key : 1 =>value: 145,155,165
key : 2 =>value: 245,255,265
DEMO Script to add user entered elements to 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










    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