HTML and CSS Reference
In-Depth Information
FORMAT
var return_value=Arrayname.shift();
Arrayname.shift( new elements); // Prepended to the array
EXAMPLE
var shifted_off = myArray.shift();
myArray.shift("blue","yellow");
EXAMPLE 9.13
<html>
<head><title>Array shift() and unshift() methods</title></head>
<body>
<script type="text/javascript">
1
var names=new Array("Dan", "Liz", "Jody" );
document.write("<b>Original array: "+ names + "<br />");
2
names.shift();
document.write("New array after the shift: " + names);
3
names.unshift("Nicky","Lucy");
// Add new elements to the beginning of the array
document.write("<br />New array after the unshift: " + names);
</script>
</body>
</html>
EXPLANATION
1
A new Array object called names is created.
2
The first element of the array is shifted off, shortening the array by 1.
3
The unshift() method will prepend to the beginning of the array the names
“Nicky” and “Lucy” , thereby making it longer by two elements (see Figure 9.16).
Figure 9.16 The Array shift() and unshift() methods.
The slice() Method. The slice() method copies elements of one array into a new
array. The slice() method takes two arguments: The first is the starting element in a range
of elements that will be copied, and the second is the last element in the range, but this
element is not included in what is copied. Remember that the index starts at zero, so that
a beginning position of 2 is really element 3. The original array is unaffected unless you
assign the result of the slice back to the original array.
 
Search WWH ::




Custom Search