js unshift()方法可以向数组的头部添加元素并返回新的数组长度,我们手写一个unshift() 方法
Array.prototype._unshift = function () {
let arr = this
let oldLen = this.length
let argLen = arguments.length
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]
console.log(arr1._unshift(7, 8, 1),arr1);
从上面代码可以看出先把元素往后移动,再添加元素,对于数组长度很大的 情况下性能是比较差的。 但是我们可以先push(), 然后再reverse() ,效率更快。 咱们手写一下push和reverse做下对比
Array.prototype._push = function () {
let arr = this
let len = arguments.length
for(let i = 0; i < len; i++) {
this[this.length] = arguments[i]
}
return this.length
}
let arr = [2, 54, 65, 3, 4]
Array.prototype._reverse = function () {
let arr = this
let j = arr.length - 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
}
可以看出reverse和push的时间复杂度要低。实际对比下
let arr = []
console.time('time1')
for(let i = 0 ;i< 10000; i++) {
arr.unshift(i)
}
console.timeEnd('time1')
let arr = []
console.time('time2')
for(let j = 0 ;j< 10000; j++) {
arr.push(j)
}
arr.reverse()
console.timeEnd('time2')
|