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>");
}
Next: How to pop (or delete at end) an element from an array using JavaScript >>
More JavaScript Articles
More By Jagadish Chaterjee