This article mainly introduces the constructors of Javascript arrays and common operations. It provides detailed explanations. We recommend this article to you.
Array Constructor
We strongly recommend that you use the array constructor because of its uncertainty in processing parameters.[]
Symbol to create a new array.
[1, 2, 3]; // Result: [1, 2, 3]
new Array(1, 2, 3); // Result: [1, 2, 3]
[3]; // Result: [3]
new Array(3); // Result: []
new Array('3') // Result: ['3']
When only one parameter is passed to the array constructor and the parameter is a number, the constructor returns an element valueundefined
Andlength
Property is set as the numeric parameter passed into the constructor. However, the index of the new array is not initialized.
This method is used only in a few cases. For example, when looping a string, this method can avoid a loop.
new Array(count + 1).join(stringToRepeat);
Summary
To sum up, we should try our best to use[]
Create a new function, instead of an array constructor, so that the code is more readable.
Common Data Operations
Because the original article of this blog post is relatively short, I plan to summarize some common array operation methods:
Add Element
1.push
-Add one or more new elements to the end of the array and return the new length of the array.
2.unshift
-Add one or more new elements to the array. The elements in the array are automatically removed and the new length of the array is returned.
3.splice
-Insert one or more new elements to the specified position of the array. The inserted element is automatically moved back and returned.[]
.
Delete Element
1.pop
-Remove the last element and return the value of this element.
2.shift
-Remove the first element and return the element value. The elements in the array are automatically moved forward.
3.splice
-Delete from specified positiondeletePos
Specified start quantitydeleteCount
Array to return the removed elements. (Note the parameter difference with that when adding an element)
Other operations
1.join
-Returns a string that concatenates each element value of the array and usesseparator
Parameters are separated.
2.slice
-The return method is used to return a part or sub-array in the array. If only one parameter is specified, the return parameter ends with the end of the array. If the parameter is negative, the return value is counted from the end of the array.start
Greaterend
Returns an empty array,slice
Instead of changing the original array, a new array is returned.
3.concat
-Concatenate multiple arrays (or strings, or arrays and strings) into an array and return a new connected array.
4.reverse
-Reverse the element (first to last and last to the first) and return the modified array.
5.sort
-Sorts array elements and returns the modified array. If there are no parameters, they are sorted in ascending alphabetical order. You can also upload a sorting method.