The constructor of an array
Because of the uncertainty of the array's constructors in handling parameters, it is strongly recommended that you use [] symbols 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 constructor of the array, and if this argument is a number, the constructor returns an array of element values undefined , and the properties of the array length are set to the numeric parameters of the Passed-in constructor. But actually the index of the new array is not initialized.
This usage can be used only in rare cases, such as looping strings, to avoid using a loop.
new Array(count + 1).join(stringToRepeat);
Summarize
To sum up, we should try to use it [] to create a new function, rather than an array constructor, so that the code will be more readable.
Data Common operations
Since the original text of this blog is relatively short, I intend to summarize some common methods of array operation:
adding elements
1. push -Adds one or more new elements to the end of the array and returns 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 back to the new length of the array.
3. splice -Inserts one or more new elements into the array at the specified position, and the elements of the insertion position are automatically moved back [] .
Delete Element
1. pop -Removes the last element and returns the element value.
2. shift -Removes the first element and returns the element value, and the elements in the array are automatically moved forward.
3. splice -Deletes the deletePos specified number of elements starting at the specified position deleteCount , and returns the removed element as an array. (Note the difference between parameters when adding elements)
Other actions
1. join -Returns a string that joins each element value of the array, separator separated by arguments.
2. slice -method to return a fragment or a child array in an array, if only one argument to return the argument to the end of the array, if the argument appears negative, then the tail count from the array, if start greater than end the return of an empty array, slice will not change the original array, Instead, it returns a new array.
3. concat -Concatenate multiple arrays (also can be strings, or a mixture of arrays and strings) into an array, returning a new array of connections.
4. reverse -Reverses the element (the top row to the last, the last row to the top), returns the modified array.
5. sort -Sort the array elements and return the modified arrays. When there are no parameters, the alphabetical order is sorted alphabetically, or a sort method can be passed in.