HTML and CSS Reference
In-Depth Information
FORMAT
Arrayname.push(new elements); // Appended to the array
EXAMPLE
myArray.push("red", "green", "yellow");
EXAMPLE 9.12
<html>
<head><title>Array push() method</title></head>
<body>
<script type="text/javascript">
1
var names=new Array("Tom", "Dan", "Liz", "Jody");
2
document.write("<b>Original array: "+ names + "<br />");
3
names.push("Daniel","Christian");
4
document.write("New array: "+ names + "</b>");
</script>
</body>
</html>
EXPLANATION
1
An Array object called names is declared and initialized.
2
The contents of the array (i.e., all of its elements) are displayed.
3
The push() method appends two new elements, “Daniel” and “Christian” , to the
end of the names array.
4
The array has grown. It is displayed in the browser window with its new elements
(see Figure 9.15).
Figure 9.15 The Array push() method before and after.
The shift() and unshift() Methods. The shift() method removes the first element of
an array and returns the value shifted off; the unshift() method adds elements to the
beginning of the array. These methods are just like pop() and push() except that they
manipulate the beginning of the array instead of the end of it.
 
Search WWH ::




Custom Search