The push () method adds one or more elements to the end of the array and returns the new length. The return value is the new length after the specified value is added to the array.
Syntax: Arrayobject.push (newelement1,newelement2,...., newelementx)
- Parameter newelement1, required. The first element to add to the array.
- Parameter newelement2, optional. The second element to add to the array.
- Parameter newelementx, optional. You can add multiple elements.
The push () method adds its parameter order to the tail of the arrayobject. It modifies the arrayobject directly, rather than creating a new array. The push () method and the Pop () method use the advanced post-stack functionality provided by the array. The method changes the length of the array.
Case 1:push ()
var arr = new Array (3); Arr[0] = "Array One" arr[1] = "Array Two" arr[2] = "Array three" Console.log (arr);//Output Primitive Group Console.log (Arr.push ("Add array Four"));
document.write (arr)
Output results
One problem is that the push adds an element without directly outputting the array after the element is added, showing only the number (length) of the array.
Case 2:
The push and pop methods of an array object are added and deleted at the end of the array, respectively. The push method has a parameter, which is the element to be added to the end of the array, and the pop method has no parameters, but instead returns the element that was deleted from the end of the array.
// Case 2: Test the Push and pop methods of an array var arr = ["Aplle", "Banana", "Orange", "Pear"]; var arr2 = [1,2,3,4]; Arr.push ("Nowamagic"); var popped = arr2.pop (); Console.log (arr); Console.log (ARR2); Console.log (popped);
The results displayed:
Resolution: Click on the button above to see "Arr.push" ("Nowamagic"); After one sentence, the elements of the ARR array add one, precisely the nowamagic we push in.
Then arr2 called the Pop method, the arr2 changed, and the output was a few.
As can be seen, the ARR2 has changed from 1,2,3,4 to. Because the original last element "4", was pop out. We used the popped variable to store the return value of the pop. You can click the button below to view it.
Talking about the push () function of JavaScript