myArray.push( [ item1 ], [ item2 ], [ ... ] ) in ECMAScript 262
Adds one or more elements to the end of the array, returning the new length.
Arguments
name | type | description |
---|---|---|
item1 | Object | [optional] The first item to add. |
item2 | Object | [optional] The second item to add. |
... | Object | [optional] etc. |
- Return Type
- Number
Description
Unlike
Array.concat()
, this method modifies the array which calls it. Also unlike that method, any arrays passed as arguments to this method are added as their own item, not as each individual piece.
var colors = [ 'red' , 'green' ];
var more = colors.concat( 'orange' , 'yellow' , [ 'black' , 'white' ] );
var newLength = colors.push( 'orange' , 'yellow' , [ 'black' , 'white' ] );
// ** more is ['red','green','orange','yellow','black','white'];
// ** colors is now ['red','green','orange','yellow',['black','white']];
// ** newLength is 5
Along with pop()
, this method allows arrays to be used as a 'stack' or 'FILO' object. The following code illustrates the push()
and pop()
methods in use.
var thingsToDo=[];
thingsToDo.push('TheLaundry');
thingsToDo.push('TheDishes');
thingsToDo.push('PlayVideoGames');
// ** thingsToDo.length is now 3
// ** thingsToDo is ['TheLaundry','TheDishes','PlayVideoGames']
var mostRecentAddition = thingsToDo.pop();
// ** mostRecentAddition is "PlayVideoGames"
// ** thingsToDo.length is now 2; pop() removed the item
// ** thingsToDo is ['TheLaundry','TheDishes']
Along with shift()
, this method allows arrays to be used as a 'queue' or 'FIFO' object. The following code illustrates the push()
and shift()
methods in use.
var thingsToDo=[];
thingsToDo.push('TheLaundry');
thingsToDo.push('TheDishes');
thingsToDo.push('PlayVideoGames');
// ** thingsToDo is ['TheLaundry','TheDishes','PlayVideoGames']
var firstThingToDo = thingsToDo.shift();
// ** firstThingToDo is "TheLaundry"
// ** thingsToDo.length is now 2; shift() removed the item
// ** thingsToDo is now ['TheDishes','PlayVideoGames']