Array constructor
Due to the uncertainty of the constructor of the array when processing parameters, it is highly recommended to use the [] symbol to create a new array.
[1, 2, 3]; // Result: [1, 2, 3]new Array(1, 2, 3); // Results: [1, 2, 3]
[3]; // Results: [3]
new Array(3); // Results: []
new Array('3') // Result: ['3']
When only one parameter is passed into the constructor of the array, and this parameter is still a number, the constructor will return an array with an element value undefined , and length property of this array is set to the numerical parameter passed to the constructor. But in fact, the index of the new array is not initialized.
This usage will only be used in rare cases, such as when looping a string, which can avoid using a loop.
new Array(count + 1).join(stringToRepeat);Summarize
To sum up, we should try to use [] to create new functions instead of array constructors, so that the code will be better readable.
Common data operations
Because the original text of this blog post is relatively short, I plan to summarize some commonly used array operation methods:
Add elements
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 beginning of the array, and the elements in the array are automatically moved backwards, returning the new length of the array.
3. splice - Insert one or more new elements into the specified position of the array, the elements at the insertion position will automatically move backwards, and return to [] .
Delete elements
1. pop - Removes the last element and returns the value of that element.
2. shift - Remove the last element and return the element value, and the elements in the array will automatically move forward.
3. splice - Delete the element of the specified number of deleteCount starting from the specified position deletePos , and returns the removed element in the array. (Note the difference between the parameters when adding elements)
Other operations
1. join - Returns a string, which joins each element value of the array together, separated by separator parameter.
2. slice - method is used to return a fragment or sub-array in the array. If only one parameter is written, return the parameter to the end of the array. If the parameter appears negative, it will count from the end. If start is greater than end , return an empty array. slice will not change the original array, but will return a new array.
3. concat - concatenate multiple arrays (can also be strings, or a mixture of arrays and strings) into an array, returning the connected new array.
4. reverse - Invert the element (the first one is ranked last, the last one is ranked last), and return the modified array.
5. sort - Sort the array elements and return the modified array. When there are no parameters, they will be sorted in ascending order of the alphabet, or you can pass a sorting method in it.