Home > Article > Web Front-end > How Can I Efficiently Add Elements to the Beginning of a JavaScript Array?
To add new elements to the beginning of an array, you can leverage JavaScript's built-in unshift method, which offers an efficient O(1) operation. This method takes any number of arguments and inserts them as new elements at the start of the array.
Usage:
array.unshift(element1, element2, ...)
Example:
Consider an array [23, 45, 12, 67]. To prepend the element 34, simply call:
array.unshift(34);
The resulting array will be [34, 23, 45, 12, 67], as desired.
Comparison to Previous Approach:
Your initial approach of creating a new array, pushing the new element, and then concatenating the old array is not only complex (O(n)) but also unnecessary. unshift achieves the same result with significantly better efficiency.
Additional Notes:
The above is the detailed content of How Can I Efficiently Add Elements to the Beginning of a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!