js add element unshift() to array
Add a new item to the starting position of the array:
Example
Add a new item to the starting position of the array:
var fruits = ["Banana", "Orange", "Apple", "Mango"]; ("Lemon","Pineapple");
fruits will output:
Lemon,Pineapple,Banana,Orange,Apple,Mango
Definition and usage
The unshift() method adds one or more elements to the beginning of the array and returns a new length.
Notice:This method will change the number of arrays.
hint:To add a new item to the end of the array, use the push() method.
js unshift performance analysis
js unshift() method can add elements to the head of the array and return the new array length. We handwritten an unshift() method
._unshift = function () { let arr = this let oldLen = let argLen = let newLen = oldLen + argLen for (let i = oldLen - 1; i >= 0; i--) { arr[i + argLen] = arr[i] } for (let i = 0; i < argLen; i++) { arr[i] = arguments[i] } return newLen } let arr1 = [1, 3, 4, 5, 6] (arr1._unshift(7, 8, 1),arr1); // 8, [7, 8, 1, 1, 3, 4, 5, 6]
From the above code, we can see that first moving the element backwards and then adding elements is relatively poor in the case of a large array length.
But we can push() first and reverse() again, which is faster.
Let's handwritten push and reverse to compare
._push = function () { let arr = this let len = for(let i = 0; i < len; i++) { this[] = arguments[i] } return } let arr = [2, 54, 65, 3, 4]
._reverse = function () { let arr = this let j = - 1 for(let i = 0; i < j; i++,j--) { let curLeft = arr[i] let curRight = arr[j] arr[i] = curRight arr[j] = curLeft } return arr }
It can be seen that the time complexity of reverse and push is low. In actual comparison
let arr = [] ('time1') for(let i = 0 ;i< 10000; i++) { (i) } ('time1') // Average time consumption 5ms
let arr = [] ('time2') for(let j = 0 ;j< 10000; j++) { (j) } () ('time2') // Average time consumption 0.47ms
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.