This series of articles mainly concentrates on working with JavaScript arrays. This is the fourth article in the series and mainly concentrates on working with multiple arrays effectively. You can reuse these scripts to inject into server side controls easily (especially in .NET and Java).
JavaScript Arrays: Pushing, Popping and Shifting - How to append an element to an array using JavaScript: discussion (Page 2 of 5 )
Within the code in the previous section, I mainly created a simple button (which is identified as “ButtonPush”). The button is defined with an “onclick” event which calls a JavaScript function, “ButtonPush_onclick”. The same function simply calls another JavaScript function named “Show.”
The function “Show” is defined as follows:
function Show() { var myArray = new Array(); myArray[0] = "Red"; myArray[1] = "Green"; myArray[2] = "Blue"; myArray[3] = "White"; document.write("Before adding<br>-------------<br>"); for (var i = 0; i < myArray.length; i++) { document.write(myArray[i] + "<BR>"); } myArray.push("aaa"); document.write("<br>After adding<br>-------------<br>"); for (var i = 0; i < myArray.length; i++) { document.write(myArray[i] + "<BR>"); } }
Let us go through the above code part by part. Let us consider the first part as follows:
var myArray1 = new Array(); myArray1[0] = "Red"; myArray1[1] = "Green"; myArray1[2] = "Blue"; myArray1[3] = "White";
The above part creates a new array named “myArray1” and adds four elements to the same array (“Red,” ”Green,” ”Blue,” and ”White”).
We use the following loop to display all the elements (as explained in my first article):
document.write("Before adding<br>-------------<br>"); for (var i = 0; i < myArray.length; i++) { document.write(myArray[i] + "<BR>"); }
The above displays only those four elements we added above (as we did not “push” anything at the moment). Further proceeding, we have the following:
myArray.push("aaa");
The above statement adds a new element, “aaa,” to the array “myArray” at the end. Once added, we need to check whether it has been added or not. I repeated the same loop (but with a different heading) as follows:
document.write("After adding<br>-------------<br>"); for (var i = 0; i < myArray.length; i++) { document.write(myArray[i] + "<BR>"); }