unshift()



The unshift method is used to add the arguments defined within the brackets as new items within an array. They are added to the top of the list, and existing elements are shifted down the list to accomodate the new items. Use the return property to ascertain the new length of the array.

syntax:

Array.unshift(argument1, argument2)

EXAMPLE

unShiftArray = new Array(50, 60);

newItems = unShiftArray.unshift(70, 80);

document.write("The items of the array are now as follows: " + unShiftArray[0] + ", " + unShiftArray[1] + ", " + unShiftArray[2] + ", " + unShiftArray[3] )

The example shows a new array being created called unShiftArray, which initially holds two values - 50 and 60. The unshift() method is then used to add two more values to the array - 70 and 80. Finally, the document.write statement writes the new contents of the unShiftArray array to the screen, with some descriptive text. You'll notice that the 70 and 80 are now before the 50 and 60 in the array, as the following output shows:



The items of the array are now as follows: 70, 80, 50, 60