Home > Article > Web Front-end > A brief discussion on adding and deleting JavaScript arrays
This article will briefly talk about adding and deleting JavaScript arrays. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Add
(1) The simplest way: assign a value to the new index
(2 ) Use push() and unshift() methods (see push and pop later)
2. Delete
(1) delete operator deletes array elements
Using delete to delete elements in an array will not modify the length attribute of the array, nor will elements be moved down from high indexes to fill the gaps left by deleted elements. Convert a non-sparse array into a sparse array.
(2) Use pop() and shuift() methods
3. Comparison of array methods for learning and memory
(1) push() and pop()
The push() and pop() methods allow arrays to be used as stacks (first in, last out). Both methods will change the original array.
The push() method adds one or more elements to the end of the array and returns the length of the new array.
The pop() method, on the contrary, deletes the last element in the array, reduces the length of the array, and returns the value of the deleted array element.
(2) unshift() and shift()
These two methods are very similar to the above two methods, but the difference is here The two methods are to insert and delete elements at the head of the array.
unshift() adds one or more elements to the head of the array and moves existing elements to a higher index to gain space. And returns the new length of the array.
shift() deletes the first element of the array and returns. Move subsequent elements down one position to fill the deleted empty elements.
When using the unshift() method to pass in multiple parameters, the order of new elements in the array is the same as the order of passing parameters
If the elements are inserted one by one in order, the final result will be the opposite
Summary: The above is the entire content of this article, I hope it can be helpful to everyone Learning helps. For more related tutorials, please visit JavaScript Video Tutorial!
Related recommendations:
The above is the detailed content of A brief discussion on adding and deleting JavaScript arrays. For more information, please follow other related articles on the PHP Chinese website!