Please tell me the understanding of the unshift and push methods in js
In JavaScript,unshift
andpush
are two commonly used methods of arrays, which are used to add elements at the beginning and end of an array respectively. Both methods are methods to change the original array, which means that they will directly modify the original array rather than create a new array.
- push method
push
The method adds one or more elements to the end of the array and returns the new array length. For example:
let arr = [1, 2, 3]; let length = (4, 5); (arr); // Output: [1, 2, 3, 4, 5](length); // Output: 5,Because the new length of the array is5
In this example,push
Methods add 4 and 5 to the arrayarr
end and return the new array length 5.
- unshift method
unshift
The method adds one or more elements to the beginning of the array and returns the new array length. For example:
let arr = [1, 2, 3]; let length = (0, -1); (arr); // Output: [-1, 0, 1, 2, 3](length); // Output: 5,Because the new length of the array is5
In this example,unshift
Methods add -1 and 0 to the arrayarr
starts with and returns the new array length 5.
Summarize:
-
push
andunshift
All are methods to change the original array. -
push
Add elements at the end of the array, andunshift
Add elements at the beginning of the array. - Both methods return the new array length.
This is the article about this article about the unshift and push methods in js. For more related contents of js unshift and push methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!